Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement browser side caching in django for dynamic files (eg If image is served from RAM )
I am using django and nginx for serving images. I use redis to store frequently accessed images. Since they're not static and not served by nginx directly,I don't know how to implement browser side caching. Image url looks like: site.com/image/image_name.jpg How should I go about generating hash,setting expire time,etc? Also how should I receive cached image's hash from browser and send 304 or invalidate the cached image? -
How do i filter many to many relationship in Django
My aim is to be able to filter by using the fields from the participants' table which I'm able to do. However, the participant table has a many to many relationship with sessions which is called in the sessions table. I'm not able to filter the participant data by filtering sessions I tried by using the related name but the filtering was unsuccessful. Can anyone help me with this as I'm still learning Django and this is my first project. participant_list.html {% load widget_tweaks%} {% block content %} <body class="sb-nav-fixed"> <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.first_name.label_tag }} {% render_field filter.form.first_name class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.last_Name.label_tag }} {% render_field filter.form.last_Name class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.country.label_tag }} {% render_field filter.form.country class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.gender.label_tag }} {% render_field filter.form.gender class="form-control" %} </div> <div> {% for choice in filter.form.organization %} <label class= "checkbox-inline"> {{ choice.tag}} {{ choice.choice_label }} </label> {% endfor %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.trainer.label_tag }} {% render_field filter.form.trainer class="form-control" %} </div> <div> {% for choice in filter.form.session %} <label class= "checkbox-inline"> {{ choice.tag}} {{ choice.choice_label }} </label> … -
Django: Join two Querysets to touple
Given two Querysets from different models, q1 = Queryset[a, b, c, d], q2 = Queryset[e, f, g, h]. How do i join them to a tuple, so the output is: Queryset[(a, e), (b, f)...]. I guess this isn't quite possible, since the Querysets are from different models. The output doesn't have to be a Queryset though, it can be a List aswell. I just want to be able to iterate over it. Thanks for your Help! -
Django computation in using aggregate method
I have this computation in my views that using filter and aggregate method first is i distinct the select the StudentSubjectGrade models and in the overall i filter the average and i use aggregate to compute the average and for every grading categories i have to multiply it by its PercentageWeight. this is the computation average = average * Grading_Categories__PercentageWeight / 100 students = StudentSubjectGrade.objects.filter( grading_Period=period).filter( Subjects=subject).order_by( 'Students_Enrollment_Records', 'Grading_Categories','id' ).values('id','Grading_Categories','Average', 'Grading_Categories__PercentageWeight') overall = StudentSubjectGrade.objects.filter( grading_Period=period).filter( Subjects=subject).aggregate(average_grade=Avg('Average') * students[ 'Grading_Categories__PercentageWeight'] / 100) this is their models class StudentSubjectGrade(models.Model): GradeLevel = models.ForeignKey(EducationLevel, on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, on_delete=models.CASCADE,null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject,on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories,on_delete=models.CASCADE,null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod,on_delete=models.CASCADE,null=True, blank=True) Gradedates = models.DateField(auto_now_add=True) Average = models.FloatField(null=True, blank=True) class gradingCategories(models.Model): CategoryName = models.CharField(max_length=500, null=True) PercentageWeight = models.FloatField() this is the error i get UPDATE when i tried this overall = StudentSubjectGrade.objects.filter( grading_Period=period).filter( Subjects=subject).aggregate(average_grade=Avg('Average') * F( 'Grading_Categories__PercentageWeight') / 100 ) I received this error -
How to debug nginx with django on docker
I have django and ngix on docker. My project returns Internal server Error. that's ok I should debug. I use docker-compose logs -f nginx but there is only this log. nginx | 172.18.0.1 - - [20/Mar/2020:13:26:15 +0000] "GET / HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" "-" And my django is works on python mangge.py runserver localserver. I guess it might be uwsgi related error. However I have no idea how to debug this. Where can i check log?? these are my docker-compose file version: '3' services: python: container_name: python build: ./python command: uwsgi --socket :8001 --module app.wsgi --py-autoreload 1 --logto /tmp/mylog.log volumes: - ./src:/code - ./static:/static ports: - "8082:8082" expose: - "8001" depends_on: - db db: image: mysql:5.7 container_name: db command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: todoList MYSQL_USER: docker MYSQL_PASSWORD: docker TZ: 'Asia/Tokyo' volumes: - ./mysql:/var/lib/mysql - ./sql:/docker-entrypoint-initdb.d nginx: image: nginx:1.13 container_name: nginx ports: - "8000:8000" volumes: - ./nginx/conf:/etc/nginx/conf.d - ./nginx/uwsgi_params:/etc/nginx/uwsgi_params - ./static:/static depends_on: - python phpmyadmin: container_name: phpmyadmin image: phpmyadmin/phpmyadmin environment: - PMA_ARBITRARY=1 - PMA_HOST=db - PMA_USER=root - PMA_PASSWORD=root links: - db ports: - 8081:80 volumes: - /sessions -
is django more secure than flask?
Django have got inbuilt security like XSS protection , CSRF protection , SQL injection protection and Clickjacking protection ,etc but flask doesnot have got inbuilt security . So it worth to tell that Django is more secure than Flask ? and for massive web application , developer should use Django instead of Flask ? -
Is there a Django built in signup view?
I know django has default account related views. the urls for them can be found in django.contrib.auth.urls. Is there a built in register view similar to those views? or do I have to implement one myself? -
how to customize the 403 error page in django?
from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import CreateView,ListView from .models import Article from django.urls import reverse_lazy class ArticleListView(LoginRequiredMixin,ListView): model = Article template_name = 'article_list.html' login_url = 'login' How can i customize the 404 error page? -
django-guardian get_objects_for_user by checking permission via ForeignKey
I have two Django Models of the form: from django.db import models class Car(models.Model): pass class Wheel(models.Model): car = models.ForeignKey(Car, related_name='wheels', on_delete=models.CASCADE) I am using django-guardian to enforce object level permissions. The real application has a very large number of nested objects, and it was found that the write performance for creating all of the permission objects for every nested object was prohibitively slow. So instead, Users are granted permissions to the top level object (Car in this toy example). On REST endpoints that access Wheel, the Django REST Framework permissions are checked by walking the foreign key upwards (in this case Wheel.car) to verify if a User should have access to a particular Wheel. How could get_objects_for_user be used to get all of the Wheels for which a User has the appropriate permission for its parent Car? Specifically trying to override django-rest-framework-guardian's ObjectPermissionsFilter.filter_queryset to support filtering objects based on the permissions of one of their ForeignKeys. -
ReadOnly views checks wrong access token in Django Rest Framework
I have a view with the following permission permission_classes = [IsOwnerOrReadOnly] the permission definition is class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True # the object has a owner attribute return obj.owner == request.user It listing of the objects works as expected if the user authenticated and pass correct access token. it also works if I do not add Authorization in header. The only problem happens when the authorization token is expired or wrong. It sends 401 response. Invalid token header. No credentials provided. How can I ignore authorization token in django code for right or wrong authorization header. -
In python what is F() mean and how to use it in django?
I search over the Internet about F() mean in python and how to use it in Django filter. its not very clear to me, on how to use it in Django. -
Annotate function with input param field value
I have a model class Audiopart(models.Model): book_id = models.ForeignKey(Audiobook, on_delete=models.CASCADE) part_title = models.CharField(max_length = 255) part_text = models.TextField(blank = True, null=True) part_reader = models.CharField(max_length = 255) filename = models.FileField(upload_to=get_upload_path, blank=True) with function def get_upload_path(instance, filename): return os.path.join( 'audio', instance.book_id.folder, filename ) I want to upload file in directory and save in database just filename (without path). But not found any way to do it. So, I make function for cleaning filename def clear_filename(_filename): if '/' in _filename: _filename = _filename.split('/')[2] return _filename How can I print my objects in view with cleaned filename? def audioparts(request, _book_id): all_audioparts = list(Audiopart.objects.filter(book_id=_book_id, published=True).values()) return JsonResponse(all_audioparts, safe=False) -
Django, pagination over multiple queryset
I'm trying to provide an api endpoint where it gives a paginated response over multiple queryset. a = Foo.objects.filter_a() b = Foo.objects.filter_b() paginator = Paginator(a + b, 10) # a + b is just symbolic, add two querysets page = 3 qs = paginator.page(page) suppose each page has 10 elements, # of a is 23 then page-3 would return 3 from a and 7 from b And we have to assume that a and b could be potentially large, and it's ideal to keep the queryset's lazyness -
Django RelatedObjectDoesNotExits - In Model init method - Setting Values works with one ForeignKey Object but not with another
My Model looks like this: class Change(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="changes") date = models.DateTimeField() category = models.ForeignKey(Category, related_name="changes", null=True, on_delete=models.SET_NULL) description = models.TextField(blank=True) change = models.DecimalField(decimal_places=2, max_digits=15) # query optimization balance = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) # for checks on save __account = None __category = None __date = None __change = None def __init__(self, *args, **kwargs): super(Change, self).__init__(*args, **kwargs) self.__date = self.date self.__category = self.category self.__account = self.account self.__change = self.change In the init method I get the following error when I try to add a new change via a form: File "/home/daniel/Data/Tortuga-Webdesign/Kunden_und_Projekte/0000/finance_project/finance/finance/banking/models.py", line 205, in __init__ self.__account = self.account File "/home/daniel/Data/Tortuga-Webdesign/Kunden_und_Projekte/0000/finance_project/venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 197, in __get__ "%s has no %s." % (self.field.model.__name__, self.field.name) finance.banking.models.Change.account.RelatedObjectDoesNotExist: Change has no account. The Form looks like this: class ChangeForm(forms.ModelForm): date = forms.DateTimeField(widget=forms.DateTimeInput(attrs={"type": "datetime-local"}, format="%Y-%m-%dT%H:%M"), input_formats=["%Y-%m-%dT%H:%M"], label="Date") class Meta: model = Change fields = ( "account", "date", "category", "description", "change" ) def __init__(self, depot, *args, **kwargs): super(ChangeForm, self).__init__(*args, **kwargs) self.fields["account"].queryset = depot.accounts.all() self.fields["category"].queryset = depot.categories.all() self.fields["date"].initial = datetime.now() The create view looks like this: class AddChangeIndexView(LoginRequiredMixin, CustomGetFormMixin, CustomAjaxFormMixin, generic.CreateView): model = Change form_class = ChangeForm template_name = "modules/form_snippet.njk" Why do I get this error with the account but not with the category? The … -
Django - how to implement totp_login custom decorator for 2FA?
In my django app, before redirecting user to 'dashboard' template, the user is first logged in, and then taken to an intermediate URL 'totp-login' for TOTP 2FA. However, I am still able to access '/dashboard' URL after logging in and is thereby able to bypass '/totp-login' URL. I need to create a custom totp_required decorator function for the same, but am unsure to be go about it. urls.py path('totp-login/', views.totp_login, name='totp-login'), path('dashboard/', views.dashboard, name='dashboard'), .... views.py @login_required def dashboard(self, request): ... Similarly for other functions/classes I need to have a similar totp_required decorator. Thanks. -
How to protect requests from Android or IOS app by using Corsheaders or others in Django without allowing all hosts?
I have created a web and mobile application using Ionic, Angular, Cordova. Server is made from Django which uses corsheaders middleware. Now for browser production, I can simply use CORS_ORIGIN_ALLOW_ALL = False and CORS_ORIGIN_WHITELIST = ('http://example.com') which will filter out untrusted request sources. However, any request coming from the mobile app version has origin 'http://localhost'. Now if I allow localhost in CORS_ORIGIN_WHITELIST, this will definitely weaken my server as any request coming from any http://localhost can access my server and this makes no sense in using corsheaders any more. How can I easily, effectively and selectively filter out non-verified request origins without compromising security? Also, could be platform-independent if possible, so same settings can serve both web, mobile and desktop apps. -
Django ORM query with exclude not working properly
I have below Django ORM query which excluding product having 0(zero) sale_price. selected_attr_values = ProductAttribValue.objects.filter(product__status_id = 1,product_id__in= product_attributes_values.values_list('product_id', flat=True).distinct()).exclude(product__sale_price = 0, field_value = '',field_value__isnull=False).distinct("field_value",'field_id').values('field_value','product_id','field__caption','field_id','id') Above query does not excluding products having 0 sale_price. But after updating query like below. selected_attr_values = ProductAttribValue.objects.filter(product__status_id = 1,product_id__in= product_attributes_values.values_list('product_id', flat=True).distinct()).exclude(field_value = '',field_value__isnull=False,).distinct("field_value",'field_id').exclude(product__sale_price = 0).values('field_value','product_id','field__caption','field_id','id') it working fine. So my question is why do I need to call exclude 2 times to get desired output. Thanks. -
Passing Form Data to View
I have the following view: views.py def PackingListView(request): if request.method == "POST": form = PackingListForm(request.POST) if form.is_valid(): if 'preview' in request.POST: request.session['data'] = form.cleaned_data return redirect('myview') .... I would like to take the data in form and pass it to this next view, and set the data variable equal to it. This was previously working, but once I added a foreign key into this form, the session no longer works as it is not serializable. What approach is the safest for me to take here? views.py class myview(View): def get(self, request, *args, **kwargs): data = request.session.pop('data', {})#this won't work now pdf = render_to_pdf('packlist_preview.html', data) return HttpResponse(pdf, content_type='application/pdf') Also in case it is needed - here is the URL for myview url(r'^myview/', views.myview.as_view(), name='myview'), -
Display error message on PasswordChangeForm
I am PasswordChangeForm form to change password. I am trying to display an error message when given password is either less than 8 or greater than 64 (in below code "form.data['new_password1']"). So when I enter password with less than 8 characters, then I am seeing error message "New password should have minimum 8 characters and maximum 64 characters" hit. But error message not displayed on UI page. This is because "return render(request, 'registration/change_password.html'" renders again. Could you please help me how can we display error message on PasswordChangeForm. @login_required(login_url='/login/') def change_password_view(request): global passwordValidationFailed passwordValidationFailed = False if (request.method == 'POST'): form = PasswordChangeForm(request.user, request.POST) if len(form.data['new_password1']) >= 8 and len(form.data['new_password1']) <= 64: if form.is_valid(): form.save() messages.success(request, 'Your password was successfully updated!') profile = request.user.get_profile() profile.force_password_change = False profile.save() return render(request, 'dau_gui_app/status_view.html', {'title': "System Status"}) else: passwordValidationFailed = False messages.error(request, 'Please correct the error below.') else: raise form.ValidationError("New password should have minimum 8 characters and maximum 64 characters") else: form = PasswordChangeForm(request.user) return render(request, 'registration/change_password.html', { 'form': form }) Here is my change_password.html {% load i18n %} {% load admin_static %}{% load firstof from future %}<!DOCTYPE html> <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}> <head> <meta charset="utf-8"> <meta … -
Create a Django REST API from a class diagram
From the knowledge I have, one has two approaches: code first or database first. There are frameworks where one defines the models and the relationships, and auto migrate creates the database in the mirror of what one has defined. Tried to find something reverse, but appears to me that Django does what I mentioned first - if one created the class models and migrated, then Django would create the entity database model for us. Considering I started with the database, I don't know anything automatic to do this or the best way to tackle it. -
Can't access python local server on docker
Can't access python local server on docker I have django project on docker At first I am trying to access django server asides nginx. Django server is docker-django-set_python container. for now please ignore other containers. my port is forwarded like this 0.0.0.0:8082->8082/tcp CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1382905adca0 nginx:1.13 "nginx -g 'daemon of…" 2 seconds ago Up 1 second 80/tcp, 0.0.0.0:8000->8000/tcp nginx 43eda3b920f8 phpmyadmin/phpmyadmin "/docker-entrypoint.…" 2 seconds ago Up 1 second 0.0.0.0:8081->80/tcp phpmyadmin c32fdf7fdbe9 docker-django-set_python "uwsgi --socket :800…" 2 seconds ago Up 1 second 8001/tcp, 0.0.0.0:8082->8082/tcp python 74bd1fe5e49c mysql:5.7 "docker-entrypoint.s…" 2 seconds ago Up 2 seconds 0.0.0.0:3306->3306/tcp, 33060/tcp db then I start, django server correctly started but it doesn't connect http://127.0.0.1:8082/. Is there any points I need to check?? $docker exec python python3 manage.py runserver 8082` Watching for file changes with StatReloader Performing system checks... Using TensorFlow backend. System check identified no issues (0 silenced). March 20, 2020 - 20:52:03 Django version 3.0.1, using settings 'myapp.myconf.local' Starting development server at http://127.0.0.1:8082/ Quit the server with CONTROL-C. -
Django admin - filter in get_queryset not working
I have this two models class Invitacion(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) host = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=256, verbose_name="Nombre Invitacion") class Invitado(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) invitacion = models.ForeignKey(Invitacion, on_delete=models.CASCADE) name = models.CharField(max_length=50) ... And registered those in the admin with admin.site.register(Invitacion) @admin.register(Invitado) class InvitadoAdmin(admin.ModelAdmin): def get_queryset(self, request): if request.user.is_superuser: return Invitado.objects.all() return Invitado.objects.filter(invitacion__host=request.user) However this filter does not work: return Invitado.objects.filter(invitacion__host=request.user) If I filter on the shell it works but not on the admin. I have an admin group that only has permission to add/change/delete Invitados -
How to all the admin to maintain content on this model
I am using Django/Wagtail I have a form and would like to allow the admin to be able to edit field titles and help text models.py class FoodDiaryItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user_pk = models.SmallIntegerField(null=True, blank=True, default=0,) date = models.DateField(null=True, blank=True) time = models.TimeField(null=True, blank=True) level_of_hunger = models.SmallIntegerField(null=True, blank=True, default=0, validators=[ MaxValueValidator(5), MinValueValidator(0) ]) ... food_diary_item.html <form action="/food-diary/diary-updated/{{ food_diary_item.id }}" method="post"> {% csrf_token %} <table> <tr><td class="text-right">Food Diary item for:</td><td>{{ user.username }}</td></tr> <tr><td class="text-right">Date:</td><td>{{ food_diary_item_form.date }}</td></tr> <tr><td class="text-right">Time:</td><td>{{ food_diary_item_form.time }}</td></tr> <tr><td class="text-right">Level of hunger:</td><td>{{ food_diary_item_form.level_of_hunger }}</td></tr> <tr><td class="text-right"> </td><td>before eating (rate from 0-5, 0=no hunger, 5=starving)</td></tr> ... Is there any way that I can re-organise the model to make the text admin maintainable? -
Confused about API relevance and Django
Im new to web development and trying to learn APIs through Django Rest Framework. I am actually confused about why we actually need to build an API. For example, I've seen tutorials of creating blog APIs, where it returns the posts and its info. Why would we need an API for that? We can simply create regular Django views to do the same. I've heard that APIs only provide the 'data', but I can also obtain data from regular Django. So why would you install a totally new 'sub' framework to do these for you? -
Django: overriding templates from oTree package
I wish to change the layout of some of the oTree templates, but I'm not sure how to override them? I've read the docs about overriding, I added the templates in settings and make my own .html files with the same name, but they still show the oTree templates. What am I doing wrong here? Settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'day_trader/day_trader/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Templates structure templates --> day_trader --> DemoIndex.html (name of the template I've made and want to override) However, it just loads the template from the oTree package. Am I suppose to create a view and return it too?