Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fetch the user saved model form data and return this to the user?
Scenario: A user has already completed a form. What's required: How do you return a completed model form in Views.py? I have followed a few guides on here such as this one with no success. Here is my shortened code containing the relevant sections: models.py APPROVAL_CHOICES = [ (None, 'Please select an option'), ("Yes", "Yes"), ("No", "No"), ] class Direct(models.Model): def __str__(self): return self.registered_company_name class Meta: verbose_name_plural = 'Company Direct Application' user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True") registered_company_name = models.CharField(max_length=250, verbose_name="Company") trading_name = models.CharField(max_length=250) registered_company_address = models.CharField(max_length=250) further_details_required = models.CharField(max_length=3, choices=APPROVAL_CHOICES, blank=True, verbose_name="Further Details Required") forms.py class CompanyDirectApplication(forms.ModelForm): class Meta: model = Direct fields = ["registered_company_name", "trading_name", "registered_company_address"] widgets = { "registered_company_name": TextInput(attrs={'class': 'form-control'}), "trading_name": TextInput(attrs={'class': 'form-control'}), "registered_company_address": TextInput(attrs={'class': 'form-control'}) } views.py if Direct.objects.filter(further_details_required="Yes", user=request.user).exists(): form = CompanyDirectApplication() form.instance.user = request.user return render(request, 'direct_application.html', {'form': form}) #otherwise render a blank model form else: form = CompanyDirectApplication() return render(request, 'direct_application.html', {'form': form}) The HTML template renders the form with a simple {{form.as_p}} -
How to solve "could not change permissions of directory "/var/lib/postgresql/data": Operation not permitted" error on Windows 10?
I am working on Windows 10 and running commands in git bash. I have following docker-compose.yml file: services: db: image: postgres:latest user: 1000:1000 volumes: - postgres-data:/var/lib/postgresql/data environment: - POSTGRES_USER='postgres' - POSTGRES_PASSWORD='postgres' ports: - 8000:8000 volumes: postgres-data: external: True I have created postgres-data volume in terminal by running docker volume create postgres-data. Then I type in docker-compose up. I have read in the Internet that I need to name a volume to run postgres. However there is still an error: initdb: error: could not change permissions of directory "/var/lib/postgresql/data": Operation not permitted On top of that, when the postgres db works on Docker, I want to add web component. I have been following a tutorial https://github.com/docker/awesome-compose/tree/master/official-documentation-samples/django/. What is missing in the docker-compose.yml? -
localhost doesn't work when I dockerize postgres with Django
My system is Ubuntu 22.04.1 LTS. I was going through the Django for professionals book and follow all line by line but somehow when i dockerize my django project with postgres it just doesn't run localhost properly, with sqlite all works fine. Dockerfile # Pull base image FROM python:3.10.6-slim-bullseye # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . docker-compose.yml version: "3.9" services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: django.settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD": "postgres", "HOST": "db", # set in docker-compose.yml "PORT": 5432, # default postgres port } } When I run docker-compose up that shows and seems like all must be fine, but somehow it just doesn't work: enter image description here And when I go to the localhost: enter image description here I spend a lot of hours of searching for info about this problem but nothing did help. I try even … -
Django xhtml2pdf
Does xhtml2pdf has bugs while using in Django 4.1.1? I am not able to display <pdf:pagenumber/> , nor <pdf:pagecount/> I am struggling to get my static files load too, I am getting SuspiciousFileOperation error. -
Django Form is not saving file to Database
views.py from .forms import palForm def add_form(request): if request.method!="POST": return HttpResponse("Method Not Allowed") else: form = palForm(request.POST, request.FILES) context = {"form": form} if form.is_valid(): form.save() messages.success(request,"Successfully Added") return render(request,"home/pal-form.html",context) else: messages.error(request,"Failed to Add") return render(request,"home/pal-form.html",context) forms.py from django import forms from .models import palabout class palForm(forms.ModelForm): class Meta: model=palabout fields =['fname','lname','dob','gender','profileImage'] models.py from pol.models import CustomUser from django.db import models class palabout(models.Model): user = models.ForeignKey(CustomUser, blank=True, null=True, on_delete=models.SET_NULL) profileImage = models.FileField() fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) gender = models.CharField( max_length=1, choices=(('m', ('Male')), ('f', ('Female'))), blank=True, null=True) dob = models.DateField(max_length=8) .html <form role="form" action="{% url 'pal:add_form' %}" method="post" class="form-style-9",enctype="multipart/form-data"> {% csrf_token %} <div id="profile-container"> <image id="profileImage" src= "{{pic.url}}" style="width:100px" /></div> <input id="imageUpload" type="file" name="profile_photo" placeholder="Photo" required="" capture> <div class="container"> <ul class="personal-details"> <li> <ul class="column"> <li> <label for="fname"><strong>First Name </strong></label> <input type="text" id="fname" tabindex="1" /> </li> </ul> </li> <li> <ul class="column"> <li> <label for="lname"> <strong> Last Name </strong></label> <input type="text" id="lname" tabindex="1" /> </li> </ul> </li> <li> <ul class="column"> <li> <tr> <td for="gender"><strong>Sex:</strong></td> <td><input type="radio" name="gender" value="male" required>Male <input type="radio" name="gender" value="female">Female</td> <td>&nbsp;</td> </tr> </li> </ul> </li> <li> <ul class="column"> <li> <label for="dob"> <strong> Date of birth </strong></label> <input type="date" id="dob" value="YY-DD-MM" max="2040-01-01" > </li> </ul> </li> <ul class="column"> <li> {% … -
Django, Mezzanine: how to enable the functionality of creating a new post?
I got Django/Mezzanine up and running, I am able to login to the admin area and create new blog posts, the posts are shown on the blog, everything works. What I still cannot figure out: is how to allow any other user of my blog to create new blogposts while just browsing the site and not being an admin? Googled a lot, couldn't find an answer :( Would be very grateful for a clue! -
How to dispaly second api response in data table in vue.js
I want to show multiple api response in same datatable Already i am showing response from first api using props.item.name in datatable How to display response data from my second api in same datatable in vue.js -
How to display a map in browser using python and DJANGO API?
I am getting difficulty while displaying my map on a web browser. I am using DJANGO API and trying to display the map (code written in python) in the form of table (using HTML). views.py def default_map(request): world= folium.Map( location=[33.5969, 73.0528], zoom_start=2) #context={'Map':world} return render(request,'home.html',context) urls.py urlpatterns = [ path('', views.home, name='home'), path('about', views.about, name='about'), path('contact', views.contact, name='contact'), path('', views.home, name="default"), path('admin/', admin.site.urls), ] home.html <td colspan="=5", rowspan="15"> {{Map}} </td> -
Having problem ' Pip install -r requirements.txt ' [closed]
this is my first project with django and python. **working on mac mini m1. visualcode. latest python for mac. ** my friend opened the whole project on other computer (windows) and told me and my teammates to copy the folder, put path of static and then run : Pip install -r requirements.txt although i tried to install everything including xampp and run server and there is a problem when it comes to setup.py uploading the req.txt and the error. enter image description here appdirs==1.4.4 asgiref==3.3.1 astroid==2.4.2 atomicwrites==1.4.0 attrs==20.3.0 autopep8==1.5.4 beautifulsoup4==4.9.3 category-encoders==2.2.2 certifi==2020.12.5 chardet==4.0.0 colorama==0.4.4 cycler==0.10.0 distlib==0.3.1 dj-database-url==0.5.0 Django==2.1.15 django-appconf==1.0.4 django-bootstrap-staticfiles==3.0.0.1 django-bootstrap4==2.3.1 django-chartjs==2.2.1 django-contrib-comments==1.9.2 django-crispy-forms==1.10.0 django-jquery==3.1.0 django-load==1.0.0 django-mysql==3.10.0 django-pandas==0.6.4 django-staticfiles==1.2.1 filelock==3.0.12 future==0.18.2 gunicorn==20.0.4 idna==2.10 importlib-metadata==2.1.1 iniconfig==1.1.1 isort==5.6.4 joblib==1.0.1 kiwisolver==1.3.1 lazy-object-proxy==1.4.3 matplotlib==3.4.2 mccabe==0.6.1 mysql==0.0.2 mysql-connector-python==8.0.22 mysqlclient==2.0.1 numpy==1.19.4 packaging==20.8 pandas==1.1.5 patsy==0.5.1 Pillow==8.3.1 pluggy==0.13.1 protobuf==3.14.0 py==1.10.0 pycodestyle==2.6.0 pydot==1.4.2 pyitlib==0.2.2 pylint==2.6.0 pylint-django==2.3.0 pylint-plugin-utils==0.6 pyparsing==2.4.7 pytest==6.2.1 python-dateutil==2.8.1 python-decouple==3.3 pytz==2020.4 requests==2.25.1 scikit-learn==0.24.2 scipy==1.7.0 six==1.15.0 sklearn==0.0 sklearn2==0.0.13 soupsieve==2.0.1 sqlparse==0.4.1 statsmodels==0.12.2 style==1.1.0 threadpoolctl==2.2.0 toml==0.10.2 typed-ast==1.4.1 Unipath==1.1 update==0.0.1 urllib3==1.26.4 virtualenv==20.2.2 whitenoise==5.2.0 wrapt==1.12.1 zipp==3.4.0 i didnt try anything because i dont know what to do.. expecting to have a solution and understanding the error.. -
How to solve a UnicodeDecodeError in django?
I'm trying to get a run out of my project and this error occurs : * 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Raised during: Blog.views.post_list The string that could not be encoded/decoded was: �� I would really appreciate it if anyone tell me how can I handle this error . here is my model : ` class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset()\ .filter(status=Post.Status.PUBLISHED) class Post(models.Model): class Status(models.TextChoices): DRAFT = 'DF','Draft' PUBLISHED = 'PB' ,'Published' title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) author = models.ForeignKey(User,on_delete=models.CASCADE ,related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default = timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2,choices=Status.choices,default=Status.DRAFT) objects = models.Manager() published = PublishedManager() class Meta: ordering = ['-publish'] indexes = [ models.Index(fields = ['-publish']), ] def __str__(self): return self.title ` here is my view.py ` def post_list(request): posts = Post.published.all() return render(request,'Blog/post/list.html',{'posts':posts}) ` everything in my administration seems to be fine .and I haven't used any wierd characters in my posts . -
Integration of third party authentication on Django Project
I have an authentication system that is built in PHP for my clients to log in using only one login credential to access different products. Mostly my web pages are written in PHP so it is easy to integrate different PHP products with the same authentication. Now I have a Django webpage and want to authenticate my clients with the same authentication system that is written in PHP, is it possible? I have three PHP files which help me with the authentication can I directly tell my Django to use these files for authentication and after success redirect to the webpage to use different features inside the webpage? -
Simultaneously logins from multiple users without using framework in django
We are working on a django project and we want to allow users to be able to access the system simultaneously. However, we are having a problem in scenarios when for example: User1 logs in then User2 logs in next, if User1 did not logout from the system, when User2 refreshes the site, User2 is able to access User1 session. How can we prevent this from happening? Without implementing an API framework. Thank you. We tried to delete the request.session when the user logs out. -
I don't have django_redirect table with migration marked applied though
As I go through django-redirects docs INSTALLED_APPS = [ 'django.contrib.sites', 'django.contrib.redirects', ] MIDDLEWARE = [ 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', ] python manage.py showmigrations redirects [X] 0001_initial [X] 0002_alter_redirect_new_path_help_text Request URL: http://127.0.0.1:8000/admin/redirects/redirect/add/ ERROR saying..... no such table: django_redirect \Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: django_redirect -
Can I build an app and website blocker using cross-platform Flutter and python?
I wanna build an application in which I can block using a particular installed application or visiting websites where I use flutter for the UI and only Python and Django for the backend. I tried searching online for this and I found that this can only happen with Java. -
JQuery / AJAX - Async view - eventlisteners not responding and .remove() is not respecting the selection
it is my first time writing JQuery/AJAX and (silly me) I'm tryng to do something quite complex actually (or at least it is for me lol). Basically I am making an infinte carousel. I am sending the paginated data through a Django view, and I am using JQuery to load it asycronously (so to not refresh the page continuously and lose the previous content). This is the relevant code (I am not including any django related code, because everything there is working just fine, the issue is in the HTML/JS. However if you want to take a look at it, just let me know) HTML <main> <div id="outside-container"> <div id="inside-container" class="infinite-container"> {% for city in cities %} {% get_weather city.name 'metric' 'it' as weather_info %} <div class="items"> <div class="data-div"> <ul> <li><b>{% destructure weather_info 'location' 'city' %}</b> </li> <li class="weather">{% destructure weather_info 'weather' 'description' %}</li> <img src="{% destructure weather_info 'weather' 'icon' %}"> <li>{% destructure weather_info 'main' 'temperature' %}</li> <li>{% destructure weather_info 'location' 'time'%}</li> </ul> </div> <img loading="lazy" class="carousel-img" src="{{city.image.url}}"> </div> {% endfor %} </div> </div> <div id="directions"> <a id="right-button">Right</a> <a id="next-slide" href="?page=2">Next</a> </div> </main> CSS body { margin: 0; padding: 0; background: linear-gradient(-45deg, #4699f8, #fff2f7, #23a6d5, #1779e9); background-size: 400% 400%; animation: … -
Why my map is not displaying using django API in html?
I am using Django API and my map is not displaying. enter image description here -
multiple arguments in logger and use them in formater - django
I want to send multiple arguments in logger messages and use them directly in formater. For example, logger.exception('Exception message, 'arg1', 'arg2') logger.warning('warning message, 'arg1', 'arg2') And in formater. I want to use args like '[%(asctime)s] %(levelname)s|%(name)s|0|0|%(message)s|%(args1)s|%(args2)s' I don't want to use *args and **kwargs for these arguments. Is there any way to implement this? Any help would be appreciated. -
Infinitely posting data to server problem with using fetch POST in JavaScript
I am a university student and this is my first time of putting all together of server, api and client sides. My problem is that first I have created an API using Django-Rest framework. When I post data to that server using fetch function in JavaScript, it keeps posting that data and does not stop until I close. In the server database, many same data have been created. I cannot figure out how to fix it. My intention was I want to post the data just once. Please help me how to do it. Thank you. -
Integrate PHP auth in Django Project
I have a PHP build authentication service for my users now I want to integrate the same authentication that I have in PHP into my Django project, Is it possible, if yes can you provide me with some material where I can read about this? or is it possible I run PHP files for authentication in my Django project rather than using Django build-in authentication? -
How to resolve AssertionError: .accepted_renderer not set on Response in Django Rest Framwork
While I am calling Django url, I get an error: AssertionError: .accepted_renderer not set on Response. My code is: from rest_framework.response import Response from rest_framework.decorators import api_view, renderer_classes from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer from myapp.models import employees from .serializers import EmployeeSerializer @api_view(('GET',)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def getData(request): employees = {'name':'Bill', 'location':'Kolkata' } return Response(employees) def getEmployees(request): employee_list = employees.objects.all() serializer = EmployeeSerializer(employee_list, many = True) return Response(serializer.data) -
How to set deafult value of django form select field in template?
How to set deafult value of django form select field in template? How to set deafult value of django form select field in template? -
Trying to kill process with root user but it says: <kill: (15307): Permission denied>
I have a shell file <save_intraday.sh> that contains docker-compose exec web python manage.py save_retail_trades_data After executing this python script import subprocess subprocess.run('./save_intraday.sh', shell=True) some django command in docker container starts running and every things works perfectly. After some time i capture every task pid that is related to command above with ps aux | grep save_retail then im executing sudo kill -9 <captured pid> The problem is after exeuting sudo kill -9 <captured pid> it says kill: (15307): Permission denied (of course 15307 is for demo). As long as i know root user is the most privileged user but its says permmission denied... I will appreciate if you help me to solve this problem I'm trying to kill task with pid with sudo kill -9 <pid> and i expect to not show me permission denied and kill the proccess -
How to initialize value of foreign key in Django form
Im trying to initialize a model form where both fields are foreign key. Model: class Subcohort(models.Model): cohort_id=models.ForeignKey(Cohort,on_delete=models.PROTECT,default=0,db_constraint=False,related_name='subcohortid') parent_id=models.ForeignKey(Cohort,on_delete=models.PROTECT,default=0,db_constraint=False,related_name='subparentid') Form: class SubcohortForm(forms.ModelForm): class Meta: model = Subcohort fields = [ "cohort_id","parent_id", ] Views: cohortidnew = Cohort.objects.latest('id').id initialvalue2={ 'cohort_id':int(cohortidnew), 'parent_id':id, } form2 = SubcohortForm(initialvalue2) if form2.is_valid(): return redirect('/dashboard') It is saying my form is not valid. Can someone explain what is the reason behind this and how to fix this? Thanks. -
Identify which exception to raise in Django Storage
I have extended the Django Storage class to integrate the on demand virus scanning. I have to raise an exception if the uploaded file contains a virus. User can upload file from Django Admin or from API interface (Django Rest Framework). I need to raise an Django Rest Framework APIException if the user upload the file using API or need to raise a Django Exception if the user upload the file from Django Admin. Is there any way to identify how the user upload the file before raise the Exception? Thanks in advance. Please find the below mentioned code snippet. # Storage.save() def save(self, name, content, max_length=None): """ Integrate clamd for scanning. """ cd = clamd.ClamdUnixSocket() try: scan_results = cd.instream(content) if scan_results['stream'][0] == 'FOUND': # I need to identify the source of the request before raise the exception return super().save(name, content, max_length) except clamd.BufferTooLongError: return logger.warning("Input file's buffer value is exceeding the allow limit.") except clamd.ConnectionError: return logger.warning("ClamAV connection cannot be established.") -
In Django trying to add images with forms
The problem is in the image field. I can't add an image though I used the image field. I want to add an image to the form. please see the pic.