Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to create a drop-down menu with database objects?
I'm trying to make a website with many categories. I want staff to be able to add categories via the back-end admin page. Then I need to display those categories and display them to the to the user on a drop-down menu. They will then select a category and submit the result. All I need help with is the models. #for back end class create_listing_category(models.Model): category = models.CharField(blank=False, max_length=20) categories = ??? class create_listing_sub_category(models.Model): category = models.CharField(max_length=25, choices=categories) #categories will be the list contents sub_category = models.CharField(blank=False, max_length=20) Thank you for helping your fellow noob out -
Django ORM exclude records using an array of dictionaries
I have similar code that return all entries from a table: all_entries = Entry.objects.all() and I have the following array: exclusion_list = [ { "username": "Tom", "start_date": 01/03/2019, "end_date": 29/02/2020, }, { "username": "Mark", "start_date": 01/02/2020, "end_date": 29/02/2020, }, { "username": "Pam", "start_date": 01/03/2019, "end_date": 29/02/2020, } ] I want to exclude all Tom's records from "01/03/2019" to "29/02/2020", all "Mark" records from "01/02/2020" to "29/02/2020" and all Pam's record from "01/03/2019" to "29/02/2020" I want to do that in a loop, so I believe i should do something like: for entry in all_entries: filtered_entry = all_entries.exclude(username=entry.username).filter(date__gte=entry.start_date, date__lte=entry.end_date) Is this correct. I am new to Django ORM. Is there a better and more efficient solution? Thank you for your help -
Working Directory not configuring Visual Studio 2019
I am creating a django site and I have created django project inside an app folder of the root directory. My folder structure looks like this . ├── .gitignore ├── .travis.yml ├── .vs │ ├── PythonSettings.json │ ├── VSWorkspaceState.json │ ├── launch.vs.json │ ├── recipe-app-api │ │ └── v16 │ │ └── .suo │ └── slnx.sqlite ├── Dockerfile ├── LICENSE ├── README.md ├── app │ ├── app │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-37.pyc │ │ │ ├── calc.cpython-37.pyc │ │ │ ├── settings.cpython-37.pyc │ │ │ ├── tests.cpython-37.pyc │ │ │ └── urls.cpython-37.pyc │ │ ├── calc.py │ │ ├── settings.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── wsgi.py │ └── manage.py ├── docker-compose.yml └── requirements.txt I have configured my launch.vs.json file like this { "version": "0.2.1", "defaults": {}, "configurations": [ { "type": "python", "interpreter": "(default)", "interpreterArguments": "", "scriptArguments": "", "env": {}, "nativeDebug": false, "webBrowserUrl": "", "project": "app\\manage.py", "name": "manage.py", "workingDirectory": "app" } ] } The problem still is that Visual Studio 2019 cannot detect that my working directory is the app folder. That's why it showing the python import is unresolved. Image of the error here Am I … -
django best way to manage CRUD in a single view
I am performing a way to Delete/update/get in a same view like class APICRUDVIEW(APIView): def get(self,request,id): .... def put(self,request,id): .... def delete(self,request,id): .... So that thing doesn't violate SRP (Single Responsibility Principle ). Like according to that a class strictly should perform a single task. Or its best way to include all these in a class in django ? -
'django' is not recognized after installing it
I'm trying to install Django. But then it seems not to be recognized: C:\Users\antoi\Documents\Programming\Learning\Django\password_generator>pip3 install django Requirement already satisfied: django in c:\python36\lib\site-packages (3.1.1) Requirement already satisfied: sqlparse>=0.2.2 in c:\python36\lib\site-packages (from django) (0.3.1) Requirement already satisfied: asgiref~=3.2.10 in c:\python36\lib\site-packages (from django) (3.2.10) Requirement already satisfied: pytz in c:\python36\lib\site-packages (from django) (2018.7) C:\Users\antoi\Documents\Programming\Learning\Django\password_generator>django -V 'django' is not recognized as an internal or external command, operable program or batch file. C:\Users\antoi\Documents\Programming\Learning\Django\password_generator>django -v 'django' is not recognized as an internal or external command, operable program or batch file. When I try to execute some commands I get nothing: C:\Users\antoi\Documents\Programming\Learning\Django\password_generator>python3 manage.py runserver