Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
User DictField in combined model serializer in Django DRF
Environment: Django 2.2.16 Django RESTFramework 3.8.2 Let's say, I wan to group my query_set to a specific format and serializer all models at a time. In the past, we used a customized model to grouping the type and then feed to the customize serializer. However, we recently trying to upgrade the Django from 1.11.x to 2.2 and so as DRF. Then, there's an error prompt and I can't fix it. I also find a link, Look like it's a known issue in DRF. AttributeError: 'DictField' object has no attribute 'partial' I defined several models and serializer. class ModelA(models.Model): job_id = models.IntegerField() type = models.CharField(max_length=16) ... Some fields class ModelASerializer(serializers.ModelSerializer) Job_id = models.IntegerField() type = models.CharField(max_length=16) ... Some fields class ModelB(models.Model): Job_id = models.IntegerField() type = models.CharField(max_length=16) ... Some fields class ModelBSerializer(serializers.ModelSerializer) Job_id = models.IntegerField() type = models.CharField(max_length=16) ... Some fields ... and many models below I create a customized model to serialize all models to specific format. class CustomizeModel: def __init__(self, Job_id): self.a = {} self.b = {} # In below, I group the query_set by 'type' a_set = ModelA.objects.filter(job_id=job_id) for obj in a_set: if obj.type not in self.a: self.a[obj.type] = [] self.a[obj.type].append(obj) b_set = ModelB.objects.filter(job_id=job_id) for obj in a_set: … -
Django REST Framework How to Efficiently Filter Calculate Model property
I have a model property of is_expired that simply returns True or False by comparing the current time with another field called Saas_expire_date. @ property def is_expired(self): current_time = timezone.now() return current_time > self.saas_expire_date How do i efficiently filter this.. I fear That using For loops will drastically affect response time especial if there is alot of data class StorePublicAPI(APIView): """ Store API for client side """ def get(self, request): """ `Get Stores` """ raw_stores = Store.objects.filter( is_approved=True, is_active=True) stores = [] for store in raw_stores: if not store.is_expired: stores.append(store) serializer = StorePublicSerializer(stores, many=True) return Response(serializer.data, status=status.HTTP_200_OK) or can you help me if finding a more effective way of calculating whether a user has paid or not? when the Saas_expire_date field reaches the current date time -
Multiple Error in view,edit a list of a model
i am trying to view and edit the my customer model- i am doing is when you open the server for first time the list of customer opens as a link . as sson as i press suppose customer 1 . the form appears well pre filled as soon as i make changes and press save button it gives me error- Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/marketing/editcustomer/2250a9b1-5d25-4bce-b426-e3a4abb45abb/POST I also have back button - I get the same error after pressing back button too! Then if I go back to the customerlist(seecustomer) and I again click on the same or any other customer it gives me the following error- Manager isn't accessible via customer instances sometimes it also gives - First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'customer'. my models.py class customer(models.Model): customerid=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) customername=models.CharField(max_length=1000) my views.py def editcustomer(request,customer_pk): global customer customer=get_object_or_404(customer,pk=customer_pk,user=request.user) if request.method=='GET': form=createcustomerform(instance=customer) return render(request,'marketing/editcustomer.html',{'customer':customer,'form':form}) else: try: form=createcustomerform(request.POST,instance=customer) form.save() return redirect('seecustomer') except ValueError: return render(request,'marketing/editcustomer.html',{'customer':customer,'form':form,'error':'Incorrect entry'}) my html form code- <form action="POST" method="POST"> {% csrf_token %} <div id="customername"> <span><label for="customername">Company Name</label></span> <input type="text" id="customername" name="customername" placeholder="Enter Company's Full name" value="{{ customer.customername}}"> </div> <button class="btn btn-primary btn-md" type="submit">Save</button> <br> <input … -
checking hased password in django gives incorrect output
i am checking password of user to give user info.but when i give correct password it throws password not correct error. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): # username = None email = models.EmailField(verbose_name='email',max_length=50,unique=True) phone = models.CharField(max_length=17,blank=True) REQUIRED_FIELDS = [ 'first_name', 'last_name', 'phone', 'username', ] USERNAME_FIELD = 'email' def get_username(self): return self.email views.py from rest_framework.authtoken.models import Token from django.contrib.auth.hashers import check_password,make_password ## My Login View class LoginView(APIView): serializer_class = CustomTokenCreateSerializer permission_classes = (AllowAny,) def post(self,request,*args, **kwargs): # Cheking email Exists if User.objects.filter(email=request.POST['email']).exists(): user = User.objects.get(email=request.POST['email']) ## check password matches if check_password(request.POST['password'],user.password): ## Creating TOken token, _ = Token.objects.get_or_create(user=user) serializer = UserCreateSerializerCustom(user) return Response({'status':True, "message":"Login SuccessFull", "user_info":serializer.data, 'token':token.key}) else: return Response({'status':False, "message":"Passord is not correct,Check Passsword again"}) else: return Response({'status':False, "message":"User Doesn't Exist,Check Email again"} ) this is login api for my project.i'm using check_password function for checking the password,i can't find a solution for this problem. -
How to get values from another app from the database in Django?
How can I get the value from another app and display that value in the template present in another app of a project in Django? I have this project dir structure:- -News-Scrap - accounts - education - home - news - models.py(The value is present here) - views.py - templates - static - templates - base.html(I want to display a value here which is present in the `news` app) Since the base.html file is out of the app, how can I display any particular value from news app's the database in this page. Here's the models.py(from news app) file:- from django.db import models class PageView(models.Model): hits = models.IntegerField(default=0) #I need this value to be displayed in my `base.html` file Here's the views.py(from news app) file:- def news_list(request, *args, **kwargs): if(PageView.objects.count()<=0): x=PageView.objects.create() x.save() else: x=PageView.objects.all()[0] x.hits=x.hits+1 x.save() context={} context = { 'object_list': queryset, 'page': x.hits } return render(request, 'news_list.html', context) If the base.html file would be inside the news app I could easily get the value by {{object.<id_label>}}, But this is not working when the base.html file is present outside the app. I am a beginner in Django and having a tough time figuring out a way to achieve this. -
How to use <iform> tag to display html page
I created a view to display all the logged in users and also created a URL for it. When I explicitly go that URL path the page works fine. But when I try to display that same page inside another page using it shows an error "Localhost refused to connect". -
How do I populate an editable form field with logged in user name in django?
I am trying to create an e-commerce application using django. The customer logs in and when placing an order he/she has to fill a form which has fields like name, phone number, date etc. Since the user has already logged in how to I pre-populate the name field with username and how do i make the field editable so that if the user wants to change the username to something else. -
How to write django code inside css style tag to link images from static directory
I want to write Django code into CSS style tag in HTML elements in order to get images from static directory. here is my original code <a href="single.html" class="img" style="background-image: url(images/image_1.jpg);"></a> i tried with the below code <a href="single.html" class="img" style="background-image: {% static 'images/image_1.jpg' %};"></a> but this isn't worked for me, how can i solve this problem? NB: i used {% load static %} to load all static files, css and js works fine but i became failed to do this. -
Creating a group through models, forms and view
I am a newbie here to Django. I am practising it for work purposes. What I am trying to achieve is to create a custom Group (adding, deleting, editing). My question is that I have a form.py that takes in a CharField, and how do I extract the particular string (or char) that the user has inputted through form, and create a group. views.py def add_group(request): if request.method == "POST": mem_info_form = MembershipsInfoForm(data = request.POST) if memberships_form.is_valid(): mem_info = mem_info_form.save() else: print(mem_info_form.errors) else: mem_info_form = MembershipsInfoForm() return render(request, 'app_memberships/addmembershipsinfo.html', {'mem_info_form' : mem_info_form }) forms.py class MembershipsInfoForm(forms.ModelForm): memberships_info_form = forms.CharField(widget = forms.TextInput(attrs = {'class' : 'form-control'})) class Meta(): model = MembershipsInfo fields = ('memberships_info') models.py class Memberships(models.Model): membership = models.CharField(max_length = 20) def __str__(self): return self.membership class MembershipsInfo(models.Model): memberships_info = models.ForeignKey(Memberships, related_name = 'memberships_info', on_delete = models.CASCADE) class MyMembership(models.Model): my_membership = models.OneToOneField(Memberships, on_delete = models.CASCADE) def __str__(self): return self.my_membership Would appreciate the assistance!