Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
LDAP vs LDAPS for Django authentication
So one of the servers that we use LDAP to authenticate against has gone down and we were told to use a different website/server if our project supports LDAPS. So we put that new link into the server line in our settings.py like so (changed some words so I don't leak info!): LDAP_SETTINGS = { 'base_dn': 'dc=central,dc=server,dc=local', 'account_suffix': 'central.server.local', 'servers': ['new.server.edu'], 'staff_groups': ['aux-jr-admins', 'aux-rsrc-reports-centraldesk-checkins'], 'superuser_groups': ['aux-admins','aux-jradmins', 'aux-to-webadmin', 'aux-dept-to-developers'] } ...and that didn't work, it just failed. I can't find anything on Google pertaining to LDAPS and Django, but when I look up LDAP vs LDAPS, I can see that they are different. More specifically, LDAPS has encryption? So my question is, is LDAPS compatible with Django? And if so, how would I implement it within my settings.py file and how would I authenticate? Would I have to decrypt information? -
Virtualbox - access to website which is hosted on virtualbox
I have a Django website, which is running on VirtualBox 6.1 with Linux Mint Cinnamon. The Virtualbox is running on a desktop with Windows 7. Internet on the VirtualBox is accessible. How can I get access to this website from Browser on my desktop? On which port should I run Django in this case? In development mode I start it as follows: python3 manage.py runserver 5000. Thank you -
How can I lookup at a TextField with Djongo? Mongodb connector for Django
Admin.py Models.py Example of a post (document) at my Mongodb: My entire code: https://github.com/mtrissi/news_site_project So, I'm trying to develop an app with Django and with a Mongodb database. I'm using Djongo as the connector. All seems to work fine, except the search at the attribute 'content' of my model 'Post'. It should work fine with a simple posts = Post.objects.filter(content__icontains=r_search). But it does not. My views.py are like this: The commented lines at my search_view() are working, they search for 'author' and 'title' attributes. But the line where I search for the 'content' attribute does not work. How can I perform a search at the 'content' attribute? -
Model Choice Field doesn't save in database-django-form
Have a model that inherit from other model. I have no problem while saving data from django admin. But when I use Model Choice Field to save from form. The form simply goes to else statement instead of going it into if form.is_valid section. forms.py class CourseForm(forms.ModelForm): class Meta(): model = Course fields = '__all__' departments = forms.ModelChoiceField(queryset=Department.objects.all().order_by('name'), required=True) views.py def addcourse(request): if request.method == 'POST': form = CourseForm(request.POST) if form.is_valid(): form.save(commit=True) messages.success(request, 'The course is added successfully.') return redirect('addcourse') else: messages.error(request, 'Subject ID already exists.') return redirect('addcourse') else: form = CourseForm() return render(request,'add_course.html', {'form':form}) When I run this code it results in Subject ID already exists irrespective of any inputs. -
How to eliminate duplicate data using if condition in django template?
Is it okay to use if condition in template views to eliminate duplicate data? Note: I have already distinct cores in my views but since i have 2 loops in 1 < tr > it duplicates some data. this is my html {% for core in cores %} {% for behavior in behaviors %} {% if core.Grading_Behavior__Grading_Behavior__Name == behavior.Grading_Behavior__Grading_Behavior__Name %} <tr> <td rowspan="2" colspan="4" class="tblcoretitle">{{core.Grading_Behavior__Grading_Behavior__Name}} 1</td> {% if core.Grading_Behavior__Grading_Behavior__GroupName == behavior.Grading_Behavior__Grading_Behavior__GroupName %} <td colspan="4" class="tblcore"> {{behavior.Grading_Behavior__Grading_Behavior__GroupName}} </td> {% else %} {% endif %} <td class="tblcore">1</td> <td class="tblcore">2</td> <td class="tblcore">3</td> <td class="tblcore">4</td> </tr> <tr> {% if core.Grading_Behavior__Grading_Behavior__GroupName == behavior.Grading_Behavior__Grading_Behavior__GroupName %} {% else %} <td colspan="4" class="tblcore">{{behavior.Grading_Behavior__Grading_Behavior__GroupName}} </td> {% endif %} </tr> {% endif %} {% endfor %} {% endfor %} this is my views.py cores = StudentsBehaviorGrades.objects.filter(Teacher=teacher) \ .filter(Students_Enrollment_Records__in=Students.values_list('id')).values('Grading_Behavior__Grading_Behavior__Name','Grading_Behavior__Grading_Behavior__GroupName').distinct('Grading_Behavior__Grading_Behavior__Name')\ .order_by('Grading_Behavior__Grading_Behavior__Name') behaviors = StudentsBehaviorGrades.objects.filter(Teacher=teacher) \ .filter(Students_Enrollment_Records__in=Students.values_list('id')).filter().values('Grading_Behavior__Grading_Behavior__Name','Grading_Behavior__Grading_Behavior__GroupName').distinct('Grading_Behavior__Grading_Behavior__GroupName')\ .order_by('Grading_Behavior__Grading_Behavior__GroupName') this is my current result this is i want result -
Which Python scheduler is the best?
Currently I am using a APScheduler for organizing recurrence tasks. For the beginning of application that was really good option but now it gives more cons than pros. I found a Celery as a good replacement. It's scalable a not like APSCheduler. Needs more resources and probably works much more efficient. But it have a one really big disadavantage. You can't add new tasks in runtime. So to summrize it, could you recommend any really good scheduler which will be scalable, async, able to add tasks in runtime and should works with python / django application? -
permissions in django with dispatch method
i'm trying to restrict users to view only the todos they have created using the dispatch method but i tried te below approach but still i'm seeing all todos appear under a user that did not create them custom user model from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): profession = models.CharField(null=True, blank=True, max_length=30) todo model from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse # Create your models here. class Todo(models.Model): title = models.CharField(max_length=120) description = models.TextField(max_length=320) to_be_done = models.DateTimeField(null=False) date_posted = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('todo_detail', args=[str(self.id)]) listview for todos class TodoListView(LoginRequiredMixin, ListView): model = Todo template_name = 'todo_list.html' login_url = 'login' def dispatch(self, request, *args, **kwargs): objects = self.objects.filter(user=self.request.user) for obj in objects: if obj.user != self.request.user: raise PermissionDenied return super().dispatch(request, *args, **kwargs) any ideas on how i can adjust to implement above said task -
In Django, how do you get a count of the records in the through table that relate back to an object?
How do you get the count of the records in a table through a through table that relate backwards? My models class Player(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) @property def appearances(self): return self.player_appearances.count() @property def runs(self): return self.players_batted_in_appearances.count() @property def rbis(self): pass # How do you get this? class Appearance(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='player_appearances') players_batted_in = models.ManyToManyField( Player, related_name='players_batted_in_appearances') rbis is a count of the records in the through table that relate back to the appearances for this player. The SQL query is: SELECT COUNT(*) as rbis FROM appearances_appearance_players_batted_in WHERE appearance_id IN (SELECT id FROM appearances_appearance WHERE player_id = 1) An analogous example An analogous example that might be more understandable to non-baseball fans: class Author(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) @property def books(self): # number return self.author_books.count() @property def times_critiqued_by_others(self): return self.authors_critiqued_books.count() @property def times_critiqued_others(self): pass # How do you get this? class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author_books') authors_critiqued = models.ManyToManyField( Author, related_name='authors_critiqued_books') How do you find out the number of times an author has critiqued other authors? -
Retrieve Financial Year data from table in django/python
I want to retrieve data from a table based on timestamp filed. If current month is Jan, Feb or Mar retrieve data from the table where timestamp falls between [(current year-1)-04-01,current year-03-31] and if current month is in between Apr to Dec retrieve data from the table where timestamp falls between [current year-04-01,(current year +1)-03-31]. I have written code something like as below, however I want to keep year dynamic and don't want this to be hard coded, it should be taking the current year as reference for defining timestamp__range as this will keep changing every year. if datetime.now.month in (1,2,3): received_points_history = ABC.objects.select_related('receiver', 'award') \ .filter(timestamp__range=["2019-04-01","2020-03-31"])\ .values('timestamp','receiver', 'award') else: received_points_history = ABC.objects.select_related('receiver', 'award') \ .filter(timestamp__range=["2020-04-01","2021-03-31"])\ .values('timestamp','receiver', 'award') -
Django admin: Dynamic multi database django admin
I'm trying to solve something that is being quite difficult for me and uis getting me too much headache. I want to have a single django admin with multiple databases. All databases should work with all models defined in models.py (complete django admin project). Database should be selected from url If solution does not require reboot server avery time we add a new db... much better. Example: www.domainname.com/customerA --> Complete Django admin with Database A www.domainname.com/customerB --> Complete Django admin with Database B www.domainname.com/customerC --> Complete Django admin with Database C For now, trying to make a first approach, I have a middleware.py file with this: request_cfg = threading.local() class MyProjectMiddleware: def __call__(self, request): request_cfg.URL_MAIN_WORD = request.build_absolute_uri().split("/")[3] response = self.get_response(request) return response class MyProjectDatabaseRouter(object): def _default_db( self ): if hasattr( request_cfg, 'URL_MAIN_WORD' ): return request_cfg.URL_MAIN_WORD else: #this will be an error throwing situation. return 'default' def db_for_read( self, model, **hints ): return self._default_db() def db_for_write( self, model, **hints ): return self._default_db() Then, in urls.py: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings urlpatterns = [ url(r'^customerA/' , admin.site.urls), url(r'^customerB/' , admin.site.urls), url(r'^customerC/' , admin.site.urls) ] This more or less works, but.... all links on django … -
Django generate pdf from a template with xhtml2pdf
I try to generate a pdf file from an html template in my django app. First i install library: pip install --pre xhtml2pdf then i create in my project folder an utiils.py file with this function: from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None i create my html template and then in my views.py file i create the class: from yourproject.utils import render_to_pdf #created in step 4 class GeneratePdf(View): def get(self, request, *args, **kwargs): data = { 'today': datetime.date.today(), 'amount': 39.99, 'customer_name': 'Cooper Mann', 'order_id': 1233434, } pdf = render_to_pdf('pdf/invoice.html', data) return HttpResponse(pdf, content_type='application/pdf') at this point in my urls.py i add the url for start pdf creation from idocuments.views import GeneratePdf ... url(r'^fatt_doc/(?P<fat_num>\w+)/$', GeneratePdf), but when i start my app and open the link i get an error: init() takes 1 positional argument but 2 were given I think the problem is in my urls.py but someone can help me to know how i can call the function for generate pdf from an url? So many thanks … -
Python removing duplicated images
I'm trying to return random but distinct images from a given directory. I have written a function that will return a random image from a directory but I need it to return distinct images, at the moment it returns images but some of them are duplicated. What is the best way to do this? Any help would be appreciated. random_image.py def random_image(image_dir): valid_extensions = ['.jpg', '.jpeg', '.png', '.gif'] rand_dir = '/static/app_pickfeel/images/' # print(rand_dir) files = [f for f in os.listdir(settings.BASE_DIR + '/app_pickfeel/static/app_pickfeel/images') if f[f.rfind("."):len(f)] in valid_extensions] print(random.choice(files)) return rand_dir + random.choice(files) -
Django admin, add model instance across generic foreign key
I am trying to allow users to add a model instance over a generic foreign key. i.e. when a content type is selected there should be an option to add an instance of that model much like when a regular foreign key is used. This is an example model. class MenuItem(models.Model): ... content_type = models.ForeignKey( ContentType, related_name="%(app_label)s_%(class)s_content_type", on_delete=models.PROTECT, null=True, blank=True ) object_id = models.PositiveIntegerField(null=True, blank=True) content = GenericForeignKey("content_type", "object_id") -
increment 30 minutes in time in loop append in list in django
Need to add the time in list from starting time and ending time given timing = timings.objects.all() monday_time = timing.monday_time teusday_time = timing.teuday_time ... x = monday_time + datetime.time('00:30') This is not working , this give the error of typeError, How to increment time and add on list. -
Obtain the last value from every sensor on my django model
I am working with Django and I am a bit lost on how to extract information from models (tables). I have a table containing different information from various sensors. What I would like to know is if it is possible from the Django models to obtain for each sensor (each sensor has an identifier) the last row of data (using the timestamp column). In sql it would be something like this, (probably the query is not correct but I think you can understand what I'm trying) SELECT sensorID,timestamp,sensorField1,sensorField2 FROM sensorTable GROUP BY sensorID ORDER BY max(timestamp); I have seen that the group_by() function exists and also lastest() but I don't get anything coherent and I'm also not clear if I'm choosing the best form. Can anyone help me get started with this topic? I imagine it is very easy but it is a new world and it is difficult to start. Greetings! -
How to catch Timeout error before DRF raise its own Timeout?
I have external API to work with it. I have my own endpoint in DRF which should send request to external API and handle response from it before I return it to client application. This is code example: serializers.py api_integration = validated_data["form"].api_integration data = dict() for field in validated_data['form_fields']: data.update(field) headers = dict() headers["Authorization"] = api_integration.token headers["Content-Type"] = api_integration.content_type try: response = requests.post( api_integration.url, data=data, headers=headers ) except requests.exceptions.RequestException: return Response({"detail": "Something went wrong"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) When I am using debug console in PyCharm and set breakepoint on return Response... line all works as well, I handle 502 error from external API and return my own response, but when this code run without debug breakpoints I get 502 BadGateway from DRF. I find only 1 decision - change timeout time in my nginx settings, but for me this is not the best decision, I want to handle this Timeout error only in this endpoint. -
Django Form Validation Error Not Showing In Template
my issue is exactly as the problem states...I am unable to get form validation errors to work. I will post what I am currently trying below. Please let me know how I can amend my code in order to get this working. Currently, I can even successfully submit the form with any name. So clearly what I have set in forms.py is not even working... forms.py class PackingListForm(forms.ModelForm): class Meta: model = PackingList fields = ['Exporter', 'Consignee', 'Reference_Number', ... ] def clean_test_value(self): data = self.cleaned_data.get('Exporter') if not Exporter == 'Jeff': raise forms.ValidationError('ahhhh Error!') return data template (packlist.html) <td rowspan="3"colspan="2">Exporter: {{ form.Exporter }} {% for error in form.Exporter.errors %} <P class='help is-danger'>{{ error }}</p> {% endfor %} </td> views.py def PackingListView(request): if request.method == "POST": form = PackingListForm(request.POST) if form.is_valid(): .....do stuff here...... else: return render(request, 'packlist.html', {'form': form}) else: form = PackingListForm() return render(request, 'packlist.html', {'form': form}) -
Django ModelChoiceField initial value not working despite it is well set up
I have the following form : class UserUpdateForm(ModelForm): class Meta: model = User fields= '__all' widgets = { 'inscription_date': forms.DateInput(format=('%d-%m-%Y'), attrs={'class': 'datepicker', 'placeholder': 'Select a date'}) } def __init__(self, *args, **kwargs): super(UserUpdateForm, self).__init__(*args, **kwargs) current_user_id = User.objects.get(id=self.instance.id).id group_name = GroupName.objects.filter( usergroup__user__id=current_user_id).get().name current_location = User.objects.filter(id=self.instance.id).values( location=F('record__location__nom')).distinct().get() self.fields['location'] = forms.ModelChoiceField( queryset=Location.objects.all(), initial=current_location['location']) def get_form(self): form = super().get_form() return form The initial value is not working. I checked and the value inside current_location['location']is correct. I tried as well to write self.initial['location'] = current_location['location'] but still not working. This is the way, I instantiate my form : @method_decorator(login_required, name='dispatch') class UserUpdateView(LoginRequiredMixin, UpdateView): model = User form_class = UserUpdateForm template_name = 'dashboard/users/user_update_form.html' def get_success_url(self): messages.success(self.request, "The user %s was updated successfully" % ( self.object.first_name)) return reverse_lazy('dashboard:users') Do you have any clues ? -
How to open a document present in EC2 server in local machine?
I deployed my Django Project in AWS EC2 server. My website got hosted successfully. Iam running a python code on click of a HTML button to open am Excel Sheet. Python code to open the excel sheet is given below: import webbrowser a_website = "C:\python\Python38\result.xlsx" webbrowser.open_new(a_website) The excel sheet is opening in the EC2 server. But I need Excel sheet to be displayed in my local machine on which Iam clicking the HTML button on the hosted Website. How will I open the Excel sheet present on EC2 server in my local machine? -
django.db.utils.OperationalError: FATAL: password authentication failed for user "hello_django"
Background I'm halfway through a tutorial on setting up Django with Docker. My problem When I try to migrate the postgresql database using the followiing command: docker-compose exec web python manage.py migrate --noinput I get the following error: django.db.utils.OperationalError: FATAL: password authentication failed for user "hello_django" My setup: Settings.py: DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, "db.sqlite3")), "USER": os.environ.get("SQL_USER", "user"), "PASSWORD": os.environ.get("SQL_PASSWORD", "password"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", "5432"), } } .env.dev: DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=hello_django_dev SQL_USER=hello_django SQL_PASSWORD=hello_django SQL_HOST=db SQL_PORT=5432 Dockerfile: FROM python:3.7.0-alpine WORKDIR /app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install --upgrade pip COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app/ Docker-compose.yml: version: '3.7' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - ./myproject/.env.dev depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=hello_django - POSTGRES_PASSWORD=hello_django - POSTGRES_DB=hello_django_dev volumes: postgres_data: Can somebody point me in the right direction? -
Django Forms Validations
Suppose I've a form for creating new user. and In the django view I'm handling data somethings like this. username = request.POST.get('username') .......... .......... Now here I've a problem that how to validate and save data into the model. By the way this is not a actual case... -
PATCH (partial=true) doesn't work in Django
I have a PATCH endpoint to change some non required data for a "Site". Through the endpoint you should be able to edit the description and supplier from a Site. The description is already working on the existing project. When I try to add the supplier to the PATCH, it doesn't update it.. View: class AdminSiteDetailView(GenericAPIView): def get_permissions(self): return IsAuthenticated(), def get_serializer_class(self): return AdminSiteDetailSerializer @swagger_auto_schema( responses={ 200: openapi.Response( _("Successfully"), AdminSiteDetailSerializer, ) } ) def get(self, request, site_pk): """ GET the data from the site. """ #somecode @swagger_auto_schema( responses={ 200: openapi.Response( _("Successfully"), AdminSiteDetailSerializer, ) } ) def patch(self, request, site_pk): """ PATCH the description of the site. """ site = get_object_or_404(Site, pk=site_pk) serializer_class = self.get_serializer_class() serializer = serializer_class(site, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() site.save() return Response(serializer.data, status=status.HTTP_200_OK) Serializer: class AdminSiteSerializer(serializers.ModelSerializer): supplier = serializers.SerializerMethodField() class Meta: model = Site fields = [ "id", "name", "supplier", ] @staticmethod def get_supplier(site): if not site.supplier: return None return SupplierSerializer(site.supplier).data class AdminSiteDetailSerializer(AdminSiteSerializer): class Meta(AdminSiteSerializer.Meta): fields = AdminSiteSerializer.Meta.fields + ["description"] class SupplierSerializer(serializers.ModelSerializer): class Meta: model = Supplier fields = ("id", "name") model: class Site(models.Model): class Meta: ordering = ("name",) name = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) supplier = models.ForeignKey( Supplier, on_delete=SET_NULL, blank=True, null=True, related_name="sites" ) -
Correct way to delete all MpttModel Entries using Django Manager
I have a Django model(Feature) sub-classing MPTTModel. As best practice for MPTT model for foreign key is to keep on_delete=PROTECT, struggling to delete all MPTT entries at once, using Feature.objects.all().delete() I can either first delete all child nodes, and then root nodes. But this does not seem efficient to me. Is there any better option ? -
Displaying ppt and word documents on Django Templates
I am working on an e-learning website that has 3 portals; Admin Teacher and Student. The Course materials are uploaded by Admin and viewed by Students. I have displayed the file using iframe. If the file is PDF, it is getting displayed within iframe, but PPT and DOC files are getting downloaded automatically. Can someone help me with how to display PPT and Doc files within Iframe? -
from django.conf import settings NOT loading dev settings
My settings are structured like: /settings/init.py /settings/base.py /settings/dev.py /settings/prod.py The constant RANDOM_VAR is set in dev.py When I do the following in e.g. urls.py from django.conf import settings print(settings.RANDOM_VAR) I get AttributeError: 'Settings' object has no attribute 'RANDOM_VAR' After further testing I see that all my database settings etc. are loaded from dev.py. But when I want to access my dev.py settings through from django.conf import settings it doesn't work. Any ideas?