Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax load url with Django
I want to pass two variables to Django function throw ajax load. my code: $( '#emp_clk' ).click( function() { emp = $( '#emp' ).val(); emp_Id = emp.split('-')[1]; $( '#extable' ).html( ' ' ).load( "{% url 'training:add_emp_student' %}?emp_Id=" + emp_Id ); }); I want to pass another variable, like $( '#emp_clk' ).click( function() { emp = $( '#emp' ).val(); emp_Id = emp.split('-')[1]; emp_Name = emp.split('-')[0]; $( '#extable' ).html( ' ' ).load( "{% url 'training:add_emp_student' %}?emp_Id=" + emp_Id + emp_Name ); what should I do !? }); -
What is the standard and safe method to modify users model in Django?
I was following a tutorial for creating custom user models for a Django application. I followed a link to the Django documentation from the tutorial but was met with the following warning: This document is for an insecure version of Django that is no longer supported. Please upgrade to a newer release! So I have been led to the question of whether using AbstractBaseUser and AbstractUser insecure? I have tried looking for other ways to modify the default users model but have had no luck so far. -
Get all ManyToManyField objects from a related ForeignKey
Goal: List of projects and for each project all members of that project I've been struggling with this for a while now; I have three models, as shown below (simplified versions of them): class Project(models.Model): name = models.CharField(max_length=200) class Workstream(models.Model): name = models.CharField(max_length=200) members = models.ManyToManyField(User) project = models.ForeignKey(Project, on_delete=models.CASCADE) class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) What I want: to show an overview of each project, including a list of people on the project. I was playing around a bit in the html template and came up with this (but this is not what I am looking for): {% for project in projects %} {{project.name}} <br> {% for workstream in project.workstream_set.all %} {{workstream.members.all}} {% endfor %} <br><br> {% endfor %} The problem with the above is that users can be in multiple workstreams and therefore show up multiple times if this is the case. A related question I have if is it is possible to get all users related to a project without having the addition for loop for workstream, I have only added this now because I did not find a way to do this directly. -
how to populate current user in django forms
i have 2 models Employee and Leave where employee is a foreign key in Leave.now when a employee is applying for a leave i want the employee name option to be limited to only the logged in user rather than all employees.can i create a custom input with read-only and send user data using {{}} ,im not able to retrieve data from input group to models here is my codes models.py class Employee(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) no_of_leaves=models.IntegerField(null=False,validators=[MinValueValidator(1), MaxValueValidator(24)],default=24) def __str__(self): return self.user.username class Leave(models.Model): employee=models.ForeignKey(Employee,on_delete=models.CASCADE,default="") start_date=models.DateField(auto_now_add=False) end_date=models.DateField(auto_now_add=False) req_date=models.DateTimeField(default=datetime.datetime.now()) approved_by=models.CharField(max_length=100,blank=True) STATUS_OPTIONS=( ("Approved","Approved"), ("Pending","Pending"), ("Declined","Declined"), ) approved=models.CharField(max_length=10,choices=STATUS_OPTIONS,default='Pending') def __str__(self): return self.employee.user.username @property def date_diff(self): return (self.end_date - self.start_date).days forms.py class leaveForm(forms.ModelForm): class Meta(): model = Leave fields = ('employee','start_date','end_date') # start_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) widgets = { 'start_date': DateInput(attrs={'type': 'date'}), 'end_date': DateInput(attrs={'type': 'date'}) } views.py @login_required def applyforleave(request): user=request.user emp=Employee.objects.get(user=user) submitted= False if request.method == 'POST': leave_form = leaveForm(data=request.POST) emp_name=employee(data=request.POST) if leave_form.is_valid() and emp_name.is_valid(): emp_name.save() start_date= leave_form.cleaned_data.get("start_date") end_date= leave_form.cleaned_data.get("end_date") days=(end_date-start_date).days days_checker=emp.no_of_leaves-days if 0 < days_checker < emp.no_of_leaves: leave = leave_form.save() leave.set_employee leave.save() submitted = True else: print("error") else: print(leave_form.errors) else: leave_form = leaveForm() return render(request,'leaveApp/leave.html', {'leave_form':leave_form, 'submitted':submitted,'emp':emp}) leave.html <div class="container"> <div class="jumbotron"> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ leave_form.as_p }} <input type="submit" name="" … -
504 timeout on AWS with nginx and gunicorn
I am running a python Django app on an AWS EC2 instance. It uses gunicorn and nginx to serve the app, the EC2 is behind an application load balancer. Occasionally I get 504 error where the entire EC2 instance becomes unreachable for everyone (including via SSH which I use all the time otherwise). I then need to restart everything which takes time. I can replicate the error by overloading the app (e.g. uploading and processing a very large image), in that case, gunicorn worker times out (I see the timeout message in logs), 504 error appears and the instance becomes unreachable. I set my gunicorn to time out in 5 minutes (300 seconds) but it falls down quicker than that. There is nothing really useful in CloudWatch logs. I am looking for ways to resolve this for all current and future cases. I.e., I want to have the situation where, if the site gets overloaded, it returns an error message as opposed to becoming completely unreachable for everyone. Is there a way to do that? -
Diffrence in update and create method of viewset django
Whenever I try to post something it posts I dont know how django is posting stuffs . Got confused in update() and create() in viewset. . I dont have create() method in my code. HOw is post method working? http_method_names = ['get', 'put','post'] def get_queryset(): //some code def update(): //some code -
How do I fix this Django in azure deployment error “Exception Type: OperationalError Exception Value: no such table?"
I have this Django app running on my computer, as a local server and I deployed it to an azure server. It works fine locally however when it runs on the azure server gives me this error. Request Method: POST Request URL: http://runnify.azurewebsites.net/route/ Django Version: 3.0.5 Exception Type: OperationalError Exception Value: no such table: pages_routerequest Exception Location: /antenv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 396 Python Executable: /opt/python/3.7.7/bin/python3.7 Python Version: 3.7.7 Python Path: ['/opt/python/3.7.7/bin', '/home/site/wwwroot', '/antenv/lib/python3.7/site-packages', '/opt/python/3.7.7/lib/python37.zip', '/opt/python/3.7.7/lib/python3.7', '/opt/python/3.7.7/lib/python3.7/lib-dynload', '/opt/python/3.7.7/lib/python3.7/site-packages'] Server time: Mon, 7 Sep 2020 11:21:54 +0000 I can't understand what is wrong, since I am not using a pages_routerequest anywhere. in my models.py I have: from django.db import models from django.contrib.postgres.fields import JSONField class Coordinates(models.Model): """Model representing a route coordinate generated (e.g. Science Fiction, Non Fiction).""" coordinates = JSONField() def __str__(self): """String for representing the Coordinates objects""" return self.coordinates class RouteRequest(models.Model): running_distance = models.FloatField() user_location = models.CharField(max_length=8000) -
How to handle 'Cancel' - django allauth linkedin
I am using allauth Django pacakge for linkedin authentification. The login is working succesfully, the problem I have is when the user chooses to Cancel the authetification. Then user gets redirected to this URL: http://127.0.0.1:8000/accounts/linkedin_oauth2/login/callback/?error=user_cancelled_login&error_description=The+user+cancelled+LinkedIn+login&state=1BOK8XL2Xu3R Which generates the authentification error which it's normal, I believe: Social Network Login Failure An error occurred while attempting to login via your social network account. {'provider': 'linkedin_oauth2', 'code': 'unknown', 'exception': None} How can I treat/avoid this error in order to have a an errorless flow ? -
How do I make Javascript inside Django code listen & respond to on click events on the front end?
I have a page which has a list of products. For each product, I have a button (Add to Cart). Once a user clicks on this button the product gets added on a side panel (aka cart). This side panel has: Quantities to be changed Delete icon - in case user wants to remove the product from the cart. So, these delete icons are created run time every time a user adds the product to the cart. Now, I have an event listener in my JS which would listen to click on the delete icon and then remove the product. But, any clicks on the delete icons are not getting responded. Funny thing is if I take the same JS code and use it in Chrome console it works. Any idea why this is not working ? -
Unable to connect Django docker image to GCP instance using GCloud Proxy
I am using cloud_proxy to connect to google cloud postgres instance. I followed the steps in GCP website https://cloud.google.com/sql/docs/postgres/connect-admin-proxy. When I run it locally using python manage.py runserver with host for db as 127.0.0.1 and port as 5432, the program is working fine. If I try to dockerize the application and run the program, I am facing the error could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Docker file services: web: build: . command: python manage.py runserver volumes: - .:/code ports: - 8000:8000 So I tried to dockerize the application using the stack overflow answer Is there a way to access google cloud SQL via proxy inside docker container modified the host in settings.py file too. Now facing the error gcloud is not in the path and -instances and -projects are empty services: web: build: . command: python manage.py runserver depends_on: - cloud-sql-proxy volumes: - .:/code ports: - 8000:8000 env_file: - ./.env.dev cloud-sql-proxy: image: gcr.io/cloudsql-docker/gce-proxy:1.16 command: /cloud_sql_proxy --dir=/cloudsql instances=abc:us-central1:def=tcp:0.0.0.0:5432 -credential_file=/secrets/cloudsql/credentials.json ports: - 5432:5432 volumes: - credentials.json:/secrets/cloudsql/credentials.json restart: always Could you please help me with this issue. My requirement is to create a docker image with Django … -
My products doesn't get deleted in django
I've been coding in the framework django for two weeks and now I am learning to delete products. Here's the html code I've done: {% extends 'base.html' %} {% block content %} <form action = '.' method= 'POST'> {% csrf_token %} <h1>Do you want to delete the product "{{ object.title }}"?</h1> <p><input type= 'submit' value = 'Yes' /> <a href='../'>Cancel</a></p> </form> {% endblock %} And the function I've coded to delete the product def product_delete_view(request, my_id): obj = get_object_or_404(Product, id = my_id) if request.method == "POST": obj.delete() context = { 'object': obj } return render(request,"products/product_delete.html", context) However, my product doesn't get deleted. -
How to get SUM of custom column in django admin?
I have this admin class UserMemberAdmin(AdminImageMixin, BaseUserAdmin): """User Member.""" change_list_template = "admin/ggbeats/user_member/change_list.html" list_display = ('username', 'email', 'get_member_gems_balance', 'gems_transaction_link', 'topup_payment_link', 'date_joined', 'is_staff') ordering = ['-date_joined'] search_field = ['username', 'email'] fieldsets = ( (None, {'fields': ('email', 'username', 'password')}), (_('Personal info'), { 'fields': ('first_name', 'last_name', 'phone_number', 'birth_date', 'gender', 'picture',) }), (_('Game info'), { 'fields': ('game_id', 'nickname', 'is_gamer', 'is_alert', ) }), (_('Permissions'), { 'classes': ('collapse',), 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions', 'role'), }), (_('Important dates'), { 'classes': ('collapse',), 'fields': ('last_login', 'date_joined', 'confirmed_at') }), ) and I add custom column like this to this admin def get_member_gems_balance(self, obj): """Get member gems balance.""" return gems_transaction_services.get_member_gems_balance(obj) get_member_gems_balance.short_description = 'GEMS' Now, I want to add total of my custom column 'get_member_gems_balance' in {% block result_list %} {{ block.super }} Gems on this page: {{ cl.gems_count }} {% endblock %} from change_list.html I create this in admin class MyChangeList(ChangeList): def get_results(self, *args, **kwargs): super(MyChangeList, self).get_results(*args, **kwargs) q = self.result_list.aggregate(gems_sum=Sum('get_member_gems_balance')) self.gems_count = q['gems_sum'] and called in my UserMemberAdmin def get_changelist(self, request): return MyChangeList But it turns out error like this Cannot resolve keyword 'get_member_gems_balance' into field. Choices are: birth_date, confirmationcode, confirmed_at, date_joined, email, first_name, game_id, game_server_member, gameservertoken, gems_transaction_member, gems_transaction_reference, gender, groups, id, inboxthread, is_active, is_alert, is_gamer, is_staff, is_superuser, last_login, last_name, … -
Use name as a primary key instead of id in a User model Django
I am building a REST Api on Django RF and React on front end. I have users and I need the users to access their accounts via their nickname, not id (users/bob, users/john etc.). I have been thinking to change a default Django pk to be a username. So that when I make a request from React, I'll user the name. My User model is pretty straightforward: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=32, unique=True) name = models.CharField(primary_key=True, max_length=64, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email But I have doubts if this is a good idea and whether I might get in some unexpected issues in the future. I have always used PK before. Is this a good practice to do it this way or should I still use IDs as a PK, show names on front end but make requests to users' IDs under the hood? -
Django collectstatic appends new hashes even though the content of static files are not changed
I'm working on a django project with cache-busting. We were using Django 1.11 and recently had to upgrade to Django 2.2. With the earlier django version, running collectstatic would generate consistent hashed filenames that wouldn't change unless the content of the file was changed. We could run collectstatic on multiple VMs and the resulting hashes would be the same, so we could use a loadbalancer to direct requests to any of the VMs. But after upgrading to Django 2.2, running collectstatic results in new hashes being generated with each run, even though the content of the static files is unchanged. Now if the request lands on a different VM, it results in 404. We use CachedFilesMixin and also pipeline. Can someone explain why the hashes are changing even though the content is unchanged? -
AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application: '******-*****-*****-*****-*********'
I am trying to allow o365 login in my Django project using "Django Microsoft Authentication Backend (https://django-microsoft-auth.readthedocs.io/en/latest/)" but I keep getting this error when i try to log in with my microsoft credentials. AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application: '******-*****-*****-*****-*********'. I have checked the links i added to my django project and in AAD but cannot figure out the problem PS: i am doing testing on my local host i.e. localhost:8000 my redirect URI in AAD is : http://localhost:8000/microsoft/auth-callback/ and i have set DEBUG = TRUE In addition, i have chosen allow accounts in any organizational directory (multi-tenant) login option -
new domain shows 404 after adding A/AAAA records (Django Project)
I have a working Django project deployed to Linode & a domain registered via Namecheap(registered a week ago). The project works fine & I've been accessing it for a while by using just the reverse DNS link shown in the Linode dashboard. I am trying to use my new domain instead of accessing via the reverse DNS link. I followed (Corey Shafer's tutorial on this & added an A/AAAA record in my Linode and added the domain name in the allowed hosts inside the settings.py file. ALLOWED_HOSTS = ['my-domain.fr', 'www.my-domain.fr'] I've waited around 4 hours but I still cannot access my web app. When I use the "WWW" version of the link i.e. www.my-domain.fr it says Not Found The requested URL was not found on this server. Apache/2.4.41 (Ubuntu) Server at www.my-domain.fr Port 80 when I use the non "WWW" link i.e my-domain.fr in chrome it says This site can’t be reached my-domain.fr’s server IP address could not be found. Try running Windows Network Diagnostics. DNS_PROBE_FINISHED_NXDOMAIN here's what I've tried. #1 Added two different A/AAAA records. With Hostname = "www" (in lowercase) along with the IP and TTL set to default With Hostname = blank, with IP & default TTL … -
write a client in Python to call a rest web service using JWT authentication
I have setup a Django REST endpoint with JSON Web Tokens (JWT) Authentication, following all the steps explained in this article. Briefly, the exposed endpoints are: http://localhost:8000/api/token/ # to get a new jwt token http://localhost:8000/api/token/refresh/ # to refresh a jwt token http://localhost:8000/hello/ # a sample web service which requires jwt authentication The example explained in the article uses djangorestframework_simplejwt package, which uses settings.SECRET_KEY (of the Django web app) to encrypt the jwt tokens (using HS256 algorithm). Also, server side, I have created a specific username ("testuser") with Django administration website to be used for JWT authorization. Now, how can I start testing this REST web service which uses JWT authentication with a client written in Python? -
InvalidCursorName error when trying to add/update rows in unmanaged postgres table using Django
I have 3 models as shown below. All the 3 are existing tables in postgres db and hence have been marked with managed=False. I am trying to add/update rows from the TourData model. The migrations have all ran fine without any errors. But everytime I try to access the url which generates the form to add/update rows in TourData model, I get a exception cursor "_django_curs_2876_sync_1" does not exist. I am unable to figure out what this means. I am not sure if the view I am using is the right way to render out the form too. I searched a lot for what this error could mean but couldn't find much information on how to solve it. Hence reaching out to the SO community experts for help. I am fairly inexperienced with Django and this is the first time I am doing anything with unmanaged models. I am using Django 3.1 and Postgres 12 in production. I also have a multiple databases setup with the default database also being a postgres db in my local machine. models.py: class Client(models.Model): firstname = models.TextField(blank=True, null=True) lastname = models.TextField(blank=True, null=True) created = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'client' … -
How to render Django model field in template form?
I'm trying to add django-faicon field in a form inside my template. I have a form like: from faicon.fields import FAIconField class SomeForm(forms.Form): icon = FAIconField() And I add the field into template: {{ form.icon }} But instead a real icon field I see on webpage: <faicon.fields.FAIconField> What is a proper way to render icon field outside Django admin? -
TypeError at /flightdetails/airlines/1 'Airlines' object is not iterable
I think since i am trying to pass only one object (id=pk),in airlines.html, for loop is not working. If I do Airlines.objects.all it works.Please help. This is my view def airlines(request,pk): content = { 'Airlinesdata':Airlines.objects.get(id=pk) } return render(request, 'airlines.html', content) This is my url. path('flightdetails/airlines/<int:pk>', views.airlines, name='airlines'), This is my airlines.html {% for order in Airlinesdata %} <tr> <td>{{order.Airline_Name}}</td> <td>{{order.Email}}</td> <td>{{order.Address}}</td> <td>{{order.Contact_Number}}</td> </tr> {% endfor %} -
Django Webhook receive post request for Mailgun
I've setup a webhook in Django to receive updates from Mailgun. The mailgun POST payload is delivered to the webhook in the below format: { “signature”: { "timestamp": "1529006854", "token": "a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0", "signature": "d2271d12299f6592d9d44cd9d250f0704e4674c30d79d07c47a66f95ce71cf55" } “event-data”: { "event": "opened", "timestamp": 1529006854.329574, "id": "DACSsAdVSeGpLid7TN03WA", // ... } } If I try and retrieve event parameter using the below code, I get an error saying TypeError: 'method' object is not subscriptable @csrf_exempt @require_POST def mailgun(request): event_data = request.POST.get['event-data']['event'] return HttpResponse(event_data, status=200) Any help is appreciated. -
Django and HTML - placing a div inside a <td> element renders it in the wrong place
I am trying to render a table element with a inside in order to do a AJAX call to replace what is contained within the . However when I look into my html page the is in the complete wrong place. I am using the {% include %} functionality of django, is this the reason? main.html <table class='table' <thead> <th>headers</th> <th>headers</th> <th>headers</th> <th>headers</th> </thead> <tr> <td> data </td> <td> data </td> {% include 'results/other_templates/data_details.html' %} </tr> </table> data_details.html <div id="{{obj.id}}-detail"> <td>blah blah blah</td> <td>blah blah blah</td> </div> Looking at my html page source when the page is rendered, it renders like this: <div id="263-detail"> </div> <table class='table'> <thead> <th>headers</th> <th>headers</th> <th>headers</th> <th>headers</th> </thead> <tr> <td> data </td> <td> data </td> <td> blah blah blah </td> <td> blah blah blah </td> </tr> </table> The div element is now outside of the table. Why would this happen? -
testdriven.io django raise 500 on heroku when tried to access postgres
I am following tutorial in https://testdriven.io/courses/tdd-django/deployment/ . Everything worked perfectly when I request get without accessing postgres, http://ancient-waters-04623.herokuapp.com/ping/ will return status 200 I done the migration and seed data $ heroku run python manage.py migrate $ heroku run python manage.py loaddata movies.json when i run http://ancient-waters-04623.herokuapp.com/api/movies/ in my browser, it will give me error 500 the logs: $ heroku logs --app=ancient-waters-04623 --tail 2020-09-07T10:13:51.045281+00:00 heroku[router]: at=info method=GET path="/ping/" host=ancient-waters-04623.herokuapp.com request_id=1895c42e-27d8-4d67-b5e8-98d0e5c3a3bd fwd="210.186.32.252" dyno=web.1 connect=0ms service=4ms status=200 bytes=225 protocol=http I tried connect the database via dbeaver, and it connected and has correct data loaded. I'm newbie in heroku either django, any help will be appreciated. Thanks in advance -
Django 2 Adding URL Parameter after {% url %} call in template
Without having to modify my urls.py, I want to manually add a URL parameter to the end of the {% url %} call in my template. Then, in my view, I want to access that query parameter's value. If lang='fr', open the French template or, if lang='en', open the English template. Here is my code: urls.py urlpatterns = [ path('<int:topic_id>/', views.tutorials, name='tutorials'), path('<int:topic_id>/<int:tutorial_id>/', views.topic_tutorial, name='topic_tutorial'), path('<int:topic_id>/<int:tutorial_id>/<slug:slug>/', views.topic_tutorial, name='topic_tutorial_keywords'), ] views.py def topic_tutorial(request, topic_id, tutorial_id, slug=None): """Show specific Tutorial by topic""" # NOTE: nothing is returned if (request.GET.get('lang')): lang = request.GET.get('lang') topics = Topic.objects.all() tutorial = Tutorial.objects.get(topic__id=topic_id, id=tutorial_id) if request.path != tutorial.get_absolute_url(): return redirect(tutorial, permanent=True) # renaming topic to avoid spaces name = tutorial.topic.text.lower() if (' ' in name): name = "_".join( name.split() ) # renaming tutorial to avoid spaces tut_name = tutorial.text.lower() if (' ' in tut_name): tut_name = "_".join( tut_name.split() ) # lang always empty if (lang == 'fr'): file = name + "-" + tut_name + "_fr.html" else: file = name + "-" + tut_name + ".html" path = 'tutorials/' + file context = {'tutorial': tutorial,'topics': topics,'file':file} return render(request, path, context) template.html <div class="card-body"> <h5 class="card-title">{{ tut.text }}</h5> <p class="card-text">{{ tut.summary }}</p> <p class="card-text"> <a href="{% url 'topic_tutorial' … -
How to add an item to database directly in django without forms
I know, this question has already been discussed, but I am unable to grab that. Here are two models I have # Create your models here. GENDER_CHOICES = [ ('Male', 'M'), ('Female', 'F')] class upload(models.Model): name = models.CharField(max_length=100,null=True) gender = models.CharField(max_length=10,null=True, choices=GENDER_CHOICES) phone = models.CharField(max_length=50,null=True) email= models.EmailField(max_length=50,null=True) file=models.FileField(upload_to='uploads/',null=True) def __str__(self): return self.name class text(models.Model): texts=models.CharField(max_length=200,null=True,blank=True) upload_text=models.ForeignKey(upload, blank=True, null=True, on_delete = models.CASCADE) I have a form for model upload. I inserted the data, and an audio file. Then I want this audio file to convert to text and save the text in the database. For that purpose, I created another model text. But I don't know how to insert the text to this model in relation to the information entered in model upload Here is my views.py file function def display(request): print('display functio') d=upload.objects.last() test=sr.takeCommand(d.file.path) print(test) **# I can see text here** p = text.objects.create(texts=test) p.save(force_insert=True) print(test) return render(request,'thanks.html',{'print':test}) But I am unable to enter it. It throws an error UNIQUE constraint failed: sub_app_text.id