Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
display allow or block popup location django
I want to display allow or block location button popup in a html page in Django and get the user's current location through IP that gives latitude and longitude. -
Django admin Page 404 Not Found & Error Handling page Not Working (DEBUG_PROPAGATE_EXCEPTIONS)
My Django Project is perfectly working Local PC , and after Deployment Please Help Me to Fix! I face Some problems: Don't show Django Error Handling Page. Django Admin Page Not Show. my setting & Urls & output File Here, I cannot see my Django default as like my development. urls.py File from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('frontend.urls')), path('admin/', admin.site.urls), #path('admission/', include('admission.urls')), path('user/', include('userregistration.urls')), path('study/', include('study.urls')), path('employment/', include('employment.urls')), #path('form/', include('form.urls')), ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) admin.site.index_title = "GSL Adminstrator" admin.site.index_header = "Global Star Admin" admin.site.site_title = "Global Star Admin" admin.site.site_header = "Global Star Admin" Settings.py file from pathlib import Path, os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'wy7o_s_pw$(71l-ta)0w1fud#7%zm3$5^n2p4ygo$an0n)ieqi' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['dev.globalstar.com.bd', 'www.dev.globalstar.com.bd'] # Application definition INSTALLED_APPS = [ 'phonenumber_field', 'dal', 'dal_select2', # 'grappelli', 'widget_tweaks', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #'admission', 'employment', #'form', 'frontend', 'study', 'travel', … -
Django ajax post throws 500 error on web host but works on localhost
I am able to send JSON data using AJAX on the local server, but, when I run the same site on the webserver, ajax post throws 500 (Internal Server Error). urls.py urlpatterns = [ path('recievejson/', views.recievejson, name='recievejson'), ] views.p @csrf_exempt def recievejson(request): if request.method == 'POST': # This condition is satisfied when hosted on localhost. import json print("DATA RECIEVED") print(request.body) else: # This condition is satisfied when onsted on web server. message = "Data not recieved" return JsonResponse({"message": 'http://domain name com/static/text/'+message}) AJAX: $.ajax({ url: "/recievejson", type: "POST", data: data, processData: false, contentType: "application/json; charset=UTF-8", success: function(data) { console.log("SUCCESS"); }, error: function(data){ console.log("fail"); } }); How to resolve this issue? -
Using Django-subdomains 'WSGIRequest' object has no attribute 'subdomain'
I am using Django-Subdomain Package and I am getting this error 'WSGIRequest' object has no attribute 'subdomain'anytime I run this view. def post(self, request): register_form = StaffRegisterationForm(request.POST) if register_form.is_valid(): staff = register_form.save() print(dir(request)) return redirect('account:dashboard', subdomain=request.subdomain) else: print(register_form.errors) return HttpResponse('form is invalid') This is my middleware in settings file: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'subdomains.middleware.SubdomainURLRoutingMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] -
Django QuerySet retuns empty queryset
I have not been able to tell why this model querry returns an empty queryset... Here are my models class Marks(models.Model): klass = models.ForeignKey(Klass,on_delete=models.SET_NULL,null=True,blank=True) stream = models.ForeignKey(Stream,on_delete=models.SET_NULL,null=True,blank=True) mark = models.IntegerField() class Klass(models.Model): name = models.CharField(max_length=20) The view. def ResultsView(request): query = request.GET.get('klass') if query: queryset = (Q(klass__name__icontains=query)) the_Student = Marks.objects.filter(queryset).distinct() all_results = {'the_Student':the_Student,'query':query} else: all_results = {} return render(request,'exams.html',all_results ) The form template <form action="{% url 'search_marks' %}" method="GET"> <div class="input-group"> <input class="" style="flex:50%" type="text" name="klass"> <button class="btn btn-primary" type="submit"></button> </div> </form> The url path('search_m',ResultsView,name='search_marks'), I try getting the results here {% for mark in the_student %} {{ mark }} {% endfor %} When I print the_student from the view it gives <QuerySet []> When I try queryset = (Q(mark__icontains=query)) brings an answer -
How to add Leaflet extensions (marker, basemap, geocoder, ...) to Django Leaflet-Map-Widget?
I set up a Django-Project with a Leaflet Map. Basically I want to fill some Input fields, draw a line on the map and then save it to admin. I created a model with different input fields. I created a form with the same fields and a "widgets = {'geom': LeafletWidget()}". In my template and view I am able to fill the input fields and draw a line on the map and then save it to django-admin/database. So far so good. BUT now I want to add more layers to the map. And I want to add some extensions like markers, geocoder for address search or layer control options. In my template I loaded the map like this: {{form.geom}} After that I tried to add the extensions like this: <script type="text/javascript"> function map_init_basic (map, options) { L.marker([51.1963, 14.3947]).addTo(map); } ... but the marker is not added to the map. If I change "map" to "id_geom-map" (as referred to in the online view) same result. Not added. I am able to set up the map manually (not a part of the form) like this at the end of the template: {% leaflet_map "map" callback="window.map_init_basic" %} ... and then I can add … -
My Flutter frontend on FlutLab does not see my Django backend on Repl.it
I am trying (unsuccessfully) to get data from my django backend, developed on repl.it, to my flutter frontend, developed on FlutLab. On Flutter side, I get data successfully from, for example, https://jsonplaceholder.typicode.com/users. On Django side, I render my data normally and get data by Postman, also without problem. But if my frontend send get() request directly to backend, I see just my circular indicator. My URL on Flutter/Dio looks like Response response = await Dio().get("https://djangobackend.myaccountname.repl.co/"); My ALLOWED_HOSTS on Django looks like ALLOWED_HOSTS = ['djangobackend.myaccountname.repl.co', '0.0.0.0:3000', 'localhost', '127.0.0.1', 'xx.xx.xx.xx'] Here 'xx.xx.xx.xx' is my IP address. Actually I have no idea which host I need to use in this case, so, I just added all I could think of. Is it possible to get data from my backend to frontend in this case and how to do it if yes? If I need another IDE, please let me know. The limitation is: I can use online IDE only. I also can provide more details if necessary. All ideas are highly appreciated! -
React component render in Django Template
I have a Django view through which I want to render a React component. But unable to do so. This is my Django template. {% extends "base.html" %} {% block javascript %} <script> window.props = {{props}}; // make sure to escape your props to prevent XSS! See here for the source for the json filter: https://gist.github.com/pirate/c18bfe4fd96008ffa0aef25001a2e88f window.react_mount = document.getElementById('react'); </script> <!-- Load React. --> <!-- Note: when deploying, replace "development.js" with "production.min.js". --> <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js" crossorigin></script> <script src="/static/components/{{component}}" type="text/babel"></script> {% endblock javascript %} {% block content %} <div class="container"> <div class="card"> <div class="card-body"> <div id="react"> <!-- Contents get replaced by mounted React.Component --> <i class="fa fa-lg fa-spinner fa-spin"></i><br><br> <i class="pending">Loading components...</i><br><br> </div> </div> </div> </div> {% endblock content%} This is my React component. import React from 'react' import ReactDOM from 'react-dom' class HelloWorld extends React.Component { render() { return <h1>Hello World!</h1>; } } ReactDOM.render( React.createElement(HelloWorld, window.props), // gets the props that are passed in the template window.react_mount, // a reference to the #react div that we render to ) I am getting following error: Uncaught ReferenceError: require is not defined -
Customize next page in Django (pagination)
so I'm building a website in Django which have similarities with YouTube. I mean there will be some thumbnails and when you click on one of them it takes you to a page where the video will be played. Now coming to the code since I don't wanna have to hard-code everything I opted to use the pagination but I have a problem cuz the pagination is doing everything automatically and I can't change the thumbnails for the next page. So either my analysis is wrong or there a way to do it correctly anyway I'm seeking your help, thanks in advance Here's the code for the template: {% load static %} {% block content %} <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3 mb-5"> <div class="col"> <div class="card shadow-sm"> <a href="{% url 'watch1' %}" target="_blank"> <img src="{% static 'thumbnails/hacker.jpeg' %}" height="225" width="100%"></a> <div class="card-body"> <p class="card-text"> {% for element in page_obj %} {% if element.category == 'boxing' %} {{ element.description|truncatechars:50 }} {% endif %} {% endfor %} </p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> </div> <small class="text-muted">9 mins</small> </div> </div> </div> </div> <div class="col"> <div class="card shadow-sm"> <a href="{% url 'watch2' %}" target="_blank"> <img src="{% static 'thumbnails/hydra.jpg' %}" height="225" width="100%"></a> <div … -
Unable to troubleshoot why search func is not working. I am not getting any errors or warnings at the cmd console
I need help to understand: the search bar is not working. So, I am expecting it to work when I input - let say CSS, then it should redirect to the CSS page. I am not getting any errors or warnings. view.py from markdown import markdown from django.shortcuts import render from django.urls import reverse from django.http import HttpResponse, HttpResponseRedirect from . import util #Search Page def search(request): value = request.GET.get('q','') if(util.get_entry(value) is not None): return HttpResponseRedirect(reverse("entry", kwargs={'entry': value })) else: subStringEntries = [] for entry in util.list_entries(): if value.upper() in entry.upper(): subStringEntries.append(entry) return render(request, "encyclopedia/index.html", { "entries": subStringEntries, "search": True, "value": value }) urls.py path("wiki/<str:entry>", views.entry, name="entry"), path("/?q=", views.search, name="search") -
How to efficiently update nested objects in Django Serializer
I have been doing some research but couldn't find an effective yet simple way to update instances without making some repetitive code. Here is an example: PartySerializer(Model.serializers) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) event_date = validated_data.get('event_date', instance.event_date) time_start = validated_data.get('time_start', instance.time_start) time_end = validated_data.get('time_end', instance.time_end) main_color = validated_data.get('main_color', instance.main_color) is_age_limited = validated_data.get('is_age_limited', instance.is_age_limited) is_open_bar = validated_data.get('is_open_bar', instance.is_open_bar) is_open_food = validated_data.get('is_open_food', instance.is_open_food) description = validated_data.get('description', instance.description) location = validated_data.get('location', instance.location) category = validated_data.get('category', instance.category) Is there any cleaner and more efficient approach ? -
Django bool field explain default is False and null is True
What does the above field specify for Django . models.BooleanField(default=False, null=True) . Does this mean Default value is False / null. -
Django admin slow loading of table with large JSON field
I have a table with a JSON field, which contains quite a bit of data. When I open the page in the admin for this table it doesn't load or takes 30+ sec to load. With exclude I can tell it to not show the JSON field when I select a single row, but can I do the same for the whole table? Admin model: class RawAPIDataAdmin(admin.ModelAdmin): list_display = ('change_id', ) exclude = ('json', ) Model: class RawAPIData(models.Model): json = models.JSONField() change_id = models.CharField(max_length=100, primary_key=True) def __str__(self): return self.change_id -
price() missing 1 required positional argument: 'self' while trying to calculate the price in Django Rest Framework
I am trying to create a case where when I call the order create api, the price will be calculated itself and saved in the database but I am getting this error in the postman. Error: price() missing 1 required positional argument: 'self My models: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) total_price = models.CharField(max_length=50,blank=True,null=True) #billing_details = models.OneToOneField('BillingDetails',on_delete=models.CASCADE,null=True,blank=True,related_name="order") def __str__(self): return self.user.email def price(self): total_item_price = self.quantity * self.item.varaints.price return total_item_price class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True #orderItem_ID = models.UUIDField(max_length=12, editable=False,default=str(uuid.uuid4())) orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) total_item_price = models.PositiveIntegerField(blank=True,null=True,default=price()) ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') Here quantity field is present in the OrderItem model itself but the price is present in the Variant model which is related to the Product model like this. Class Variants(models.Model): ...#other fields price = models.DecimalField(decimal_places=2, max_digits=20,default=500) Class Product(models.Model): ...#other fields variants = models.ManyToManyField(Variants,related_name='products') My serializer: class OrderSerializer(serializers.ModelSerializer): billing_details = BillingDetailsSerializer() order_items = OrderItemSerializer(many=True) user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Order fields = ['id','user','ordered_date','order_status', 'ordered', 'order_items', 'total_price','billing_details'] # depth = 1 def … -
Save baseball innings pitched decimal
I don’t really even know where to begin with this. I have a Django form in which I am saving baseball stats to my database. The problem I an having is with innings pitched. In baseball, innings are measured in thirds but instead of .33, .66, .99, each third is represented as .1, .2, .0 For example a pitcher could throw 5 innings, 5.1, 5.2, 6. How can store and manipulate data this way? Thanks for your help. -
Checking duplicate objects before saving
Good day SO: How to check if items are duplicate before saving? I got an answer similar to my question but I need to add a validation also who created the item. The answer that I am currently using is from this SO Answer by @dokkaebi. It is currently working, however, if other users also created the same record, I would like them to be able to do so. Only limit this to the current user. What I did was: def clean(self, *args, **kwargs): cleaned_data = super().clean() job_title = cleaned_data.get("job_title") others = cleaned_data.get("others") matching_job_item = PropositionItem.objects.filter(job_title=job_title, others=others) if self.instance: matching_job_item = matching_job_item.exclude(pk=self.instance.pk, status="0") if matching_job_item.exists(): msg = u"Job Tile: %s has already exist." % job_title raise forms.ValidationError(msg) else: return self.cleaned_data What I want: User A can't create a duplicate item while User B can create what user A created but only once. -
Firebase authentication and Backend server
I have a front-end React web app, and I am using Firebase authentication for the authentication. On the back-end I am using Django with Firebase admin to verify the Firebase user token. Could you help me understand these points: The front-end web app is sending the current Firebase user's token with the request header, and the back-end is verifying the request's authorization header token. Since the Firebase admin SDK verifies it with the public key it downloads from the google's server, and it lasts for 24 hours. Does this mean that there won't be any performance difference with every front-end request as Firebase admin will not request Google API for the verification for 24 hours? For my class models with user object and its related items (e.g.: User object, Post, Photos, etc), do I store the primary key as the Firebase user's UID? If not how should I query for the items of a user? Any help of suggestions are appreciated! Thank you. -
What is Django function request argument?
What is the meaning of request in this function argument? def home(request): return render(request, "home.html") -
FieldError at / Cannot resolve keyword 'title_icontains' into field. Choices are: complete, create, decription, id, title, user, user_id
I'm getting an error while making the search functionality for my to-do list in Django. I was following dennis ivy's tutorial, did the same thing what he did but I'm still getting the error. My code: class TaskList(LoginRequiredMixin, ListView): model = Task context_object_name = 'tasks' # For each user def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tasks'] = context['tasks'].filter(user= self.request.user) context['count'] = context['tasks'].filter(complete = False).count() search_input = self.request.GET.get('search-area') or '' if search_input: context['tasks'] = context['tasks'].filter( title_icontains = search_input) # <= Here I get the error context['search_input'] = search_input return context What is going wrong? -
How to remove last file after new file saved in Django
I'm using Django Ajax to update user avatar.What I want is after saving the new avatar ,system will delete the old one, because I want to each user only have one avatar stored in database to save space. Here is my views.py: def user_detail(request, username): profile_user = get_object_or_404(User, username=username) form = UserAvatar(request.POST or None, request.FILES or None) if request.is_ajax(): if form.is_valid(): form.save() return render(request, 'user/user_detail.html', { 'profile_user': profile_user, 'form': form, }) forms.py: class UserAvatar(ModelForm): class Meta: model = User fields = ['avatar'] Any friend can help? -
Django website can't obtain client IP through request.META
I am building a Django website that deployed on the Lightsail server. I followed this instruction https://docs.bitnami.com/aws/infrastructure/django/get-started/deploy-django-project/ and the website deployed successfully. I want to obtain the clients IP address, and I found this post on StackOverflow How do I get user IP address in django? The IP address I obtained from request.META.['REMOTE_ADDR'] is the Lightsail server IP address, not the client IP address. And I cannot get anything from request.META.get('HTTP_X_FORWARDED_FOR'), since there is no 'HTTP_X_FORWARDED_FOR' key in the request. I was wondering how do I get the client IP address through HTTP_X_FORWARDED_FOR key in the request? Thank you. -
Django passthrough API request to hide credentials
I need to make a request to b.com/rest/foo to get json data for my application. I want to do it this way to protect the credentials rather than expose them on every page. I found Consume an API in Django REST, server side, and serve it ,client side, in Angular and the corresponding answer at https://stackoverflow.com/a/65672890/2193381 to be a great starting point. I created a local url to replicate the data that the external server will return and then tried the following import requests from django.http import JsonResponse def getdata(request, item): url = f"http://localhost:8080/rest/{item}" username = os.getenv('SITE_USERNAME', None) password = os.getenv('SITE_PASSWORD', None) userpass = dict(username=username, password=password) data = requests.get( url, auth=requests.auth.HTTPBasicAuth(**userpass), ) if data is not None and data.status_code == 200: try: return JsonResponse(data.json(), safe=False) except ValueError: print("!JSON") return JsonResponse({}) print("!data") return JsonResponse({}) urlpatterns = [ path('foo/<str:item>, getdata), ] When I test it with python manage.py runserver 8080 and call localhost:8080/foo/, I am getting back the html of the login page and not the data I am expecting. What changes do I need to make to get it to work? -
AttributeError: 'ForeignObjectRel' object has no attribute 'through'
When I run python3 manage.py test test.test_attribute i get this error: AttributeError: 'ForeignObjectRel' object has no attribute 'through' I am in a tox virtual environment, and I run django-admin --version which gives me 2.2.18. I have postgreSQL. How to solve this? -
UniqueConstraint doesn't respect the condition
On my django application I try to get a unicity constraint on 2 fields depending on the value of the third one. But it seems that the condition is ignored. My model: class Accomodation(models.Model): name = models.CharField(max_length=200, unique=True) number = models.CharField(max_length=100, unique=True) category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name='accomodations') description = models.TextField() company = models.ForeignKey(Company, on_delete=models.DO_NOTHING) price = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) is_active = models.BooleanField(default=True) class Meta: default_permissions = () permissions = ( ("can_delete_accomodation", "Can delete accomodations"), ("can_create_accomodation", "Can create a new accomodation"), ) constraints = [ UniqueConstraint(fields=['company', 'name'], condition=Q(is_active=True), name='Unique_accomodation_name_per_company'), UniqueConstraint(fields=['company', 'number'], condition=Q(is_active=True), name='Unique_accomodation_number_per_company') ] So what I try to do is one company can have only one accomodation name which is active at the same time. Same for the number. Basicaly the behaviour needed is: add Accomodation(name='toto', number='1', is_active=True) <- OK add Accomodation(name='toto', number='2', is_active=True) <- Fail (name exists) add Accomodation(name='tata', number='2', is_active=True) <- Fail (number exists) change Accomodation(name='toto', number='1', is_active=False) <- OK add Accomodation(name='toto', number='1', is_active=True) <- Ok But right now I have this behaviour: add Accomodation(name='toto', number='1', is_active=True) <- OK add Accomodation(name='toto', number='2', is_active=True) <- Fail (name exists) add Accomodation(name='tata', number='2', is_active=True) <- Fail (number exists) change Accomodation(name='toto', number='1', is_active=False) <- OK add Accomodation(name='toto', number='2', is_active=True) <- Fail … -
how to read the uploaded csv file and validate for the header column values and add them if not present, using rest API in django
I'm currently working on how to update a csv file and reading the file that is uploaded from the Django admin page using rest API. I'm able to validate a particular type of file to be uploaded however finding it difficult to read the file that has been uploaded and search for the columns if present in the csv, use if for calculations and plotting graphs, if a particular column is not present I need to add them in the dashboard even before using it inside the code. so could you help me out to give a validation message saying "This ( ) column is missing in the uploaded file, please add the field" and take a post request from the dashboard simultaneously. thank you in advance! here is the type of csv file uploaded time,amplitude 0,0.73904 0.02441,1.2372 0.04883,1.0019 0.07324,0.50924 0.09766,-0.603 0.12207,-1.6674 0.14648,-1.5332 0.1709,-0.85486 0.19531,0.3971 0.21973,1.3604 0.24414,1.8384 0.26855,1.7446 0.29297,0.73904 0.31738,-0.69308 0.3418,-1.6969 with this they can also upload a csv file missing either of the row, and we need to give a validation method for each. this is my views.py file from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status from .serializers import …