Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run django project - localhost with ssl
In the Django project, Is any way possible to enable SSL(https) in the localhost environment? Example, the application should run https://localhost:8000 instead of http://localhost:8000 -
Set up different CORS rules based on the endpoint in Django
I'm trying to figure out a way to have different CORS rules based on the backend endpoint frontend would hit. So I can have /api endpoint with a CORS domain whitelist and /public-api without a CORS domain whitelist. This is needed because I have both internal endpoints I use for my own frontend, and a public JS widget that can be installed in any 3rd party domain. I've looked at django-cors-headers library, but it's regex configuration CORS_ORIGIN_REGEX_WHITELIST = [] works to let requests FROM a list of domains through. I'm looking for a way to have a regex to let requests TO my endpoints through or not. -
django rest framework calculate/modify result before sending to browser
view: class ChartAPIView(RetrieveAPIView): serializer_class = ChartSerializer queryset = Chart.objects.prefetch_related('attendees__person').all() def get_object(self): user = self.request.user last_updated = user.profile.data_last_updated user_events = self.queryset.filter(user=user).order_by('-created') data = { 'total': user_events.count(), 'last_updated': last_updated, "chart_data": user_events } return type('DashboardData', (), data)() Serializer: class DashboardSerializer(serializers.Serializer): total = serializers.IntegerField(read_only=True) last_updated = serializers.DateTimeField(read_only=True) chart_data = EventSerializer(read_only=True, many=True) Result: { "total": 2, "last_updated": "2020-09-22 04:49:25", "chart_data": [ { "title": "Daily Stand-up", "organizer": "mailbox@phanig.com", "duration": "0:30", "attendees": "soubhagyakumar666@gmail.com, mailbox@phanig.com", "created": "2020-08-25 06:11:54", "updated": "2020-09-17 04:50:25" }, { "title": "Daily Stand-up", "organizer": "mailbox@phanig.com", "duration": "0:30", "attendees": "soubhagyakumar666@gmail.com, mailbox@phanig.com", "created": "2020-08-25 06:11:54", "updated": "2020-09-17 04:50:25" }, { "title": "Daily Stand-up", "organizer": "mailbox@phanig.com", "duration": "0:30", "attendees": "soubhagyakumar666@gmail.com, mailbox@phanig.com", "created": "2020-08-25 06:11:54", "updated": "2020-09-17 04:50:25" } ] Here is my code and results i am getting . But, before sending result to browser i wants to do some modification Is there any way we can achive that. Basically i wants to modify user_events data by passing it to a utils function. Please have a look. Expected result: [{'created': '2020-08-24', 'duration': 510}, {'created': '2020-08-25', 'duration': 1260}] I have already the function which is converting to it but, as the user_events is a query set i amgetting error while getting the key. -
How to give an static file path as JSON item in a django project
I've started a django project for first time. I want to use ajax in it to show profile items after login. in my login app's views.py file, I have this code snippet: response = {'loggedIn': logged_in, 'name': name, 'userLevel': user_level, 'photo': userPhoto} # Return response as a JSON return HttpResponse(json.dumps(response)) If I set: userPhoto = static('home/image/ProfilePicture.png') Django gives me error: Object of type URLPattern is not JSON serializable So I use: userPhoto = str(static('home/image/ProfilePicture.png'))[15:][0:-16] to cast it to string and omit header and trail. but it gives me home/image/ProfilePicture.png not static URL. I even use userPhoto =finders.find('home/image/ProfilePicture.png') but it gives me local address (i.e. file:///d:/.../ProfilePicture.png') I've googled it but I couldn't find a way to find static URL of my files Out Of Templates. I become so appreciate if you help me to find a solution... -
Celery stops executing tasks when there's around ~1000 tasks queued
We currently have a Django server that queues different asynchronous tasks like sending a batch of push notifications, sending an email, process transactions and a few other tasks. This server queues a PeriodicTask that is picked up by Beat and sent to a Redis broker. This is then picked up by different Celery workers in another server that ends up performing the task in question. This is our configuration CELERY_RESULT_BACKEND = "config.backend:CustomDataBaseBackend" CELERY_ACCEPT_CONTENT = ["json"] CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_SERIALIZER = "json" CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler" CELERY_BEAT_SYNC_EVERY = 1 CELERY_IGNORE_RESULT = False CELERY_SEND_EVENTS = True CELERY_SEND_TASK_ERROR_EMAILS = False CELERY_SEND_TASK_SENT_EVENT = True CELERY_TASK_RESULT_EXPIRES = None CELERY_BEAT_SCHEDULE = { 'clean-expired': { 'task': 'celery.clean_expired', 'schedule': crontab(hour=0), }, } Everything has been working fine for the past few months. In peak hours (10am-11am) we can handle around 4K~ tasks total, but lately we're getting more and more traffic and there's a point where the the workers stop completing tasks or do so very very slowly. Beat keeps sending tasks to Redis so this only gets worse and does not heal after time, I have to disable almost all pending tasks and re enable them slowly in order to get everything executed (or at least the things … -
pass value from django views to js function as a parameter
I have used a function which will open a tab on press of a button and those button will be generated by using values from django i am able to call those values out site the js function but when i try to pass them as parameter in js function my page shows blank. index.html {% for exp in experience %} <button class="tablinks" onclick="openCity(event, {{exp.e_name}})" id="defaultOpen">{{exp.e_name}}</button> {% endfor %} app.js function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active";} kindly guide me how can i pass exp.e_name to js function -
AssertionError: 200 != 302 : Response didn't redirect as expected: Response code was 200 (expected 302)
I am testing user redirect link and I get above stated error, read similar answers but none of them helped. Can anyone help me with this error? def test_redirection(self): url = reverse('account_signup') data = { 'username': 'john', 'email': 'john@123.com', 'password1': 'passw1', 'password2': 'passw1', } response = self.client.post(url, data) self.assertRedirects(response, reverse('projects:home')) Thank You ! -
Stripe: Setting up a card for future payments that is 3d secure authenticated
I've implemented the steps described in this Stripe tutorial on how to save card information to be used later on (future payments): https://stripe.com/docs/payments/save-during-payment This is now implemented and works fine. I'm doing a 0.5$ charge on the card to trigger the 3d secure authentication process. How it works is that it first checks what is the PaymentIntent status, and if its "action_required" then it redirects to this HTML where I've implemented in JS the following: function _3dsec(stripe_publishable_key, pi_secret) { document.addEventListener("DOMContentLoaded", function(event) { var stripe = Stripe(stripe_publishable_key); stripe.confirmCardPayment(pi_secret).then(function(result) { if (result.error) { $("#3ds_result").text("Error!"); $("#3ds_result").addClass("text-danger"); } else { $("#3ds_result").text("Card succesfully validated"); $("#3ds_result").addClass("text-success"); } }) }) } And this also works well, it does the 3D secure authentication if the card requires it. I've been testing only with Stripe cards. and then the idea is that i refund the 0.5$ as it was just used to authenticate the card. However, in my product the charges are done afterwards. There is only a signup page with the user and payment information and then charges occur as the user is using my product. This works well for cards that dont need the 3D secure authentication, but for the cards that require the authentication I'm not … -
Django 2 databases - updating data in one db with data from other db
i have some general questions for the following situation: I have a Django project that uses a MySql DB. I have full rights on this db. I have access over a ssh tunnel to another db where i have read rights. I need data from the second db. I have to retrieve data in a timely manner like every 5 minutes. I have to get like only the new entries and update some information which can change over time in different tables. The ssh connection is established and it work. Retrieving the data is also a straight forward thing. But my problem is how do i retrieve data every 5 minutes. is https://docs.python.org/3/library/sched.html a good idea? how do i get only the new entries.(the entries that appeared from last read) lets say first selection has a,b,c entries. the second has a,b,c,d,e,f,g,h. I would only need to enter d to h in my db since a to c are already there. how do i update entries in my database according to changes in the second database. lets say entry 'a' has changed. how do i update it via update statements in my db? Has anyone any idea, hints, tipps or documentation? … -
Purpose of square brackets when doing aggregate, sum and filter
In the below I am trying to understand the purpose of ['total__sum'] or 0. I have tried to Google it but I am not entirely sure what to Google. Can anyone provide a simple explanation or point me the in the direction of some relevant documentation? new_qs = qs.filter(updated__day=new_time.day, updated__month=new_time.month) day_total = new_qs.totals_data()['total__sum'] or 0 def totals_data(self): return self.aggregate(Sum("cart__total"),Avg("cart__total")) -
Django REST framework - disable BrowsableAPIRenderer when not authenticated
I'm using BrowsableAPIRenderer (default as part of Django REST). But for security reasons, I don't want it to be active if the user is not authenticated. The reason is that for example, the BrowsableAPIRenderer shows the name of View implementing it, which exposes to the user whether this API even exists. Which is considered bad practice security-wise. The reason I want to keep it when the user is authenticated is to be able to use the deubg_toolbar when not in production (but still avoid the user being able to see the BrowsableAPIRenderer if not authenticated) Example of exposed response even when the user is not authenticated (The name of the view is GetDetails, which should not be exposed, as it indicates whether a View exists): -
Django - Static images render
I have a template that should render picture of each product. But as result - URL for it has extra "static" in path like that - 127.0.0.1:8000/static/static/photos/product1.png. It should be just 127.0.0.1:8000/static/photos/product1.png Is there any way to do it properly? model.py saves it to "static/photos" class Product(models.Model): title = models.CharField(max_length=20) photo = models.ImageField(upload_to='static/photos', default='http://placehold.it/700x400') views.py from django.shortcuts import render # Create your views here. from .models import Category, Product def product_list(request): queryset = Product.objects.all() context = {"object_list": queryset} return render(request, "product_list.html", context) template.html is following {% load static %} {% for instance in object_list %} <p><img src="{% static instance.photo %}" /></p> {% endfor %} -
How to refer to django foreign key?
I used to use a OneToOneField relation to the User model, but I had to switch to foreign key (because I want to store multiple dates for 1 user). And now I can't seem to figure out how to refer to my data inside my view. view.py def get_data(request, *args,**kwargs): data = { 'weight': request.user.user_profile.weight, 'goal': request.user.user_profile.goal, 'date': request.user.user_profile.created_at, } return JsonResponse(data) models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from datetime import date # Create your models here. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_profile') weight = models.FloatField(max_length=20, blank=True, null=True) height = models.FloatField(max_length=20, blank=True, null=True) goal = models.FloatField(max_length=20, blank=True, null=True) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def save_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) -
Creating pdf with reportlab
I am Rendering HTML template to pdf in django and downloading it. i have been trying with reportlab but i am not able to do it. Can anyone help me with generating pdf with reportlab with this same code as i dont want to render from html. Thanks in advance. def download_pdf(self, request): context = { "invoice_id": 123, "customer_name": "John Cooper", "amount": 1399.99, "today": "Today", # "data": data } csv_file_id = request.GET.get("csv_file_id") data = AICSVFileOutput.objects.filter(csv_file_id=csv_file_id) # print(csv_data) context = { "invoice_id": 123, "customer_name": "John Cooper", "amount": 1399.99, "today": "Today", "data": data } pdf = render_to_pdf('pdf/duplicate_defects_org_updated.html', context) # print(pdf) if pdf: response = HttpResponse( pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" % ("12341231") filename = "output.pdf" content = "inline; filename='%s'" % (filename) download = request.GET.get("download") if download: content = "attachment; filename=%s" % (filename) response['Content-Disposition'] = content return response return -
KeyError: "Key 'field_name' not found in 'ModelForm'. Choices are: ...,
Fields are existed in the model and also added in the form class but still getting the KeyError: "Key 'budget_documents' not found in 'BudgetForm'. Choices are: address, models.py class Budget(TimeStampedModel): title = models.CharField(max_length=100) budget_documents = models.FileField(verbose_name='Budget Documents', upload_to='BIN/%Y/%m/%d/', null=True, blank=False), amount = models.BigIntegerField() allocation_date = models.DateField() expire_date = models.DateField() project = models.ForeignKey(Project, on_delete=models.PROTECT, related_name='budget') address = models.ForeignKey(Address, on_delete=models.PROTECT, blank=True, null=True, related_name='budget') creator = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): return self.title class Meta: managed = True forms.py class BudgetForm(forms.ModelForm): class Meta: model = Budget exclude = ('creator',) def __init__(self, *args, **kwargs): super(BudgetForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( Row( Column('title', css_class='col-md-6 mb-0'), Column('budget_documents', css_class='col-md-6 mb-0'), ), Row( Column('amount', css_class='col-md-6 mb-0'), Column('allocation_date', css_class='col-md-6 mb-0'), ), Row( Column('expire_date', css_class='col-md-6 mb-0'), Column('project', css_class='col-md-6 mb-0'), ), ) everything seems OK but why getting this error? 2020-09-22 17:58:14,387 WARNING Could not resolve form field 'budget_documents'. Traceback (most recent call last): File "/home/riajul/PycharmProjects/bms/venv/lib/python3.8/site-packages/django/forms/forms.py", line 155, in __getitem__ field = self.fields[name] KeyError: 'budget_documents' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/riajul/PycharmProjects/bms/venv/lib/python3.8/site-packages/crispy_forms/utils.py", line 70, in render_field bound_field = form[field] File "/home/riajul/PycharmProjects/bms/venv/lib/python3.8/site-packages/django/forms/forms.py", line 157, in __getitem__ raise KeyError( KeyError: "Key 'budget_documents' not found in 'BudgetForm'. Choices are: address, allocation_date, … -
How can I get my homepage URL in Django views.py?
I am trying some condition in my code: If request.META.get('HTTP_REFERER') == 'www.example.com/': # code here else: return redirect('/') Writing the full path https://www.example.com/ also works, but I need Django itself do. Is there any way that Django itself return my homepage URL ? -
Page view refers to id, whil path is not asking for one
This error drives me crazy. I hope someone can point me in the right direction. Summary I want to load a default django page. Nothing fancy. However, the error I get, hints at an id that is incorrectly set. "Field 'id' expected a number but got 'zoekboek'." The confusing things here (I am a django beginner, so I wouldn't be surprised if this is not confusing at all for you): the path for this page in the urls.py is not asking for an id. the view is not querying anything yet (I found some posts that had similar errors, but related to a filter). the debug info points to another view that indeed is requesting an id. when I add a slash at the beginning of the path, the error is gone! The code urls.py urlpatterns = [ path('', views.scholen, name='scholen'), path('<school_id>', views.school_detail, name='school_detail'), path('<school_id>/<groep_id>', views.school_groep, name='school_groep'), path('<school_id>/<groep_id>/<UserProfile_id>', views.leerling_page, name='leerling_page'), path('zoekboek', views.zoekboek, name='zoekboek'), ] views.py from django.shortcuts import render, redirect, reverse, get_object_or_404 from books.models import Book, Rating from .models import School, Groep from profiles.models import UserProfile, Hobby, Sport from django.contrib.auth.models import User # Create your views here. def scholen(request): """ Homepage for participating schools. """ scholen = School.objects.all() context = … -
Store Datetime field in localtime in Django
I use Django 3 with postgresql. USE_TZ is False and TIME_ZONE is 'Asia/Baku'. django.utils.timezone.now() correctly return Baku localtime, but all DateTimeFields with auto_now_add save datetime in UTC in database. I want to use localtime everywhere in my app. edit: I use ubuntu server and timezone is set on Baku -
uwsgi django skip logging specific endpoint
I'm using Django 2.2 using Dockerfile and uWWSGI in the docker to run the application ... EXPOSE 8000 ## Tell uWSGI where to find your wsgi file: ENV UWSGI_WSGI_FILE=qcg/wsgi.py # Base uWSGI configuration (you shouldn't need to change these): ENV UWSGI_HTTP=:8000 UWSGI_MASTER=1 UWSGI_HTTP_AUTO_CHUNKED=1 UWSGI_HTTP_KEEPALIVE=1 UWSGI_LAZY_APPS=1 UWSGI_WSGI_ENV_BEHAVIOR=holy # Number of uWSGI workers and threads per worker (customize as needed): ENV UWSGI_WORKERS=2 UWSGI_THREADS=4 # uWSGI static file serving configuration (customize or comment out if not needed): ENV UWSGI_STATIC_MAP="/static/=/static_cdn/static_root/" UWSGI_STATIC_EXPIRES_URI="/static/.*\.[a-f0-9]{12,}\.(css|js|png|jpg|jpeg|gif|ico|woff|ttf|otf|svg|scss|map|txt) 315360000" The application is deployed on AWS ECS usng the Dockerfile with the above uWSGI configuration. The load balancer is configured for health check at /ping/ which return pong in response with 200 status code. The AWS CloudWatch logs are filled with /ping/ requests making it difficult to analyse the log in the AWS CloudWatch. Is it possible to move these ping logs to a different Log Group or skip from the logging? -
Django objects has no attribute get error
i have this error and what is reason ? what's mean get error and what is solution about this task ? AttributeError: 'Aries' object has no attribute 'get' [22/Sep/2020 11:30:51] "GET /aries HTTP/1.1" 500 65607 Views.py def Zodiac(request): forms = Aries.objects.all() args = {'forms':forms} return render(request,'html/aries.html',args) html Daily <div class="period_date"> {% block text %} {% endblock text %} {% for date in forms %} {%if forloop.last%} Published on {{date.pub_date}} {% endif %} {% endfor %}</div> {% endblock text %} model.py class Aries(models.Model): pub_date = models.DateField() body_text = models.TextField() love_text = models.TextField(null=True) -
Multi Nested with Django Restframework and Mongodb
I want output like this. I have a task to complete more than 5 models with nested type and all CRUD methods by using RestFawork.If anyone knows the answer share with me. { "id": 1, "first_name": "John 1", "last_name": "Robert 1", "instrument": "KeyBoard", "album_musician": [ { "id": 3, "artist": 1, "name": "Test robert", "release_date": "2020-09-16", "num_stars": 400 "Language": [ { "Original": "English", "Dubbed": "Tamil" } ] } ] } In this Code, I did only Sigle Nested Framework. My model.py Serializer.py In this Serialization, I used the CRUD method class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album fields = ('id', 'artist', 'name', 'release_date', 'num_stars') class MusicianSerializer(serializers.ModelSerializer): album_musician = AlbumSerializer(many=True) class Meta: model = Musician fields = ('id', 'first_name', 'last_name', 'instrument', 'album_musician') lookup_field=id def create(self, validated_data): albums_data = validated_data.pop('album_musician') musician = Musician.objects.create(**validated_data) for album_data in albums_data: Album.objects.create(artist=musician, **album_data) return musician def update(self, instance, validated_data): albums_data = validated_data.pop('album_musician') albums = (instance.album_musician).all() albums = list(albums) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.instrument = validated_data.get('instrument', instance.instrument) instance.save() for album_data in albums_data: album = albums.pop(0) album.name = album_data.get('name', album.name) album.release_date = album_data.get('release_date', album.release_date) album.num_stars = album_data.get('num_stars', album.num_stars) album.save() return instance -
How to host the django web app on website like example.come
I tried to find on google, searched a lot of sites but I don't find any way to Host a Django web app. Provide me a proper guide of Python Django web app hosting. 2nd thing is: I have to access my own system for the directories and files, I don't want to upload the whole project on Github as bcoz it'll be an insecurity issue. -
Django import adding Many-to-Many relationship based on value non-model field
I'm using django-import-export to import an xls. In the xls is a boolean field is_senior which is not a model field. In the model I have a Many-to-Many relationship to a Model Level which has junior, senior etc. If is_senior is True I want to: senior = Level.objects.filter(name__icontains = 'senior').first() instance.level.add(senior) But the problem is: before_import_row knows the non-model field, but can't add m2m relationships after_save_instance doesn't have the non-model field any ideas? -
im using git and if try to push changes i get error which says the branches have diverged
I was working with a project in that I made a mistake so I restored my last commit in my local rep I don't know how to do it on the remote repo , no if I try to push my changes I get a error , that the branches have diverged , what should I do should I delete the remote repo and then again push ? -
Is there a reason why django doesn't pass site header context to password reset form?
I'm trying to set the site header of the password reset form but doing the admin.site.site_header = "Site header" changes the header for all other forms other than the password reset form. Is this by design and if so why? The only way I can find to fix this right now is https://stackoverflow.com/a/53572673/5562041