Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django current path didn't match, for loal host port 8000 but works properly on other
I have built a Django app and I am trying to test it locally, but the path of one of the pages is not matching with anything in the URL patterns when I am running it on http://127.0.0.1:8000/, but all the pages are working on other ports. What could be the possible reason for that? -
How to swap the primary of a Postgresql in a django way?
Good day SO. I want to swap out a Primary Key on my Postgresql with a django migration(if it matters) I tried changing it on PGAdmin but it wont let me update since there are tables that uses is connected by Foreign Key. Models: class JobsMajor(models.Model): job_title = models.CharField(max_length=100, default='', null=False) class JobsMinor(models.Model): job_major = models.ForeignKey("JobsMajor", on_delete=models.CASCADE) Data: JobMajor_1 jobMinor_1 jobMinor_2 jobMinor_3 jobMinor_4 JobMajor_2 jobMinor_5 jobMinor_6 JobMajor_3 jobMinor_7 jobMinor_8 I want to swap PK of JobMajor_2 to JobMajor_3. Reason, I want to swap the order when I get the objects of Job Major with order_by('-id') -
Images not loading when deploying Django app to Heroku
I deployed my app to heroku: https://doggos-only.herokuapp.com/ The images on the Dog Images link work locally, but they do not work on the deployed version. The only useful error I'm getting is: cj_eOAaboi.jpg:1 Failed to load resource: the server responded with a status of 404 (Not Found) My best guess is that it has something to do with the file path, but I'm not sure. I've tried looking around the web for a solution but have been unable to find one. Looking for any help, here is the repo: https://github.com/jpchato/doggos_only_project I'm deploying from the deploy_branch in my repo. -
How to create a Django website to post articles?
I'm new to django and I really have no idea how should I structure a website for the purpose of posting articles (like tutorials). I'm not asking for specific code, but how does it work? Should I make a base template and a html file for every single article that I'll post? If so, how should be the folder structure in the project? How can I show a list of all those articles and redirect to them if a user clicks on it? Should I link them to a database entry? How can I do that? I'm asking those things because I only did things that involved reading content from the database/model and showing it on a template, but articles need images and other special construction that a blog textfield would not be enough. If it is too confusing, just say so, and I'll try to put in another words, I'm really struggling to put my question into words. -
Im having an issue where it says my form is invalid when I submit it?
models.py class Contact(models.Model): BookID = models.CharField(max_length=30) BookTitle = models.CharField(max_length=30) Author = models.CharField(max_length=35) UploadImage = models.ImageField(upload_to='ContactImg') def __str__(self): return self.BookId views.py def ContactUs(request): user_form=ContactForm() if request.method == 'POST': user_form = ContactForm(request.POST) if user_form.is_valid(): # we load our profile instance Contact.BookId = user_form.get('BookId') Contact.BookTitle = user_form.get('BookTitle') Contact.Author= user_form.get('Author') Contact.UploadImage= user_form.get('UploadImage') Contact.save() return redirect('readingTime:home') else: # Invalid form # messages.error(request, 'Form contains errors. Double check') print(user_form.errors) messages.error(request, 'Form contains errors. Double check') # user_form = user_form.errors # user_form = RegisterForm() else: # Blank form since we do not have an HTTP POST user_form = ContactForm() return render(request,"readingTime/ContactUs.html") Forms.py class ContactForm(forms.Form): BookID=forms.CharField(max_length=30,required=True) BookTitle=forms.CharField(max_length=30,required=True) Author=forms.CharField(max_length=35,required=True) UploadImage=forms.ImageField() class Meta: model = Contact fields = ('BookID', 'BookTitle', 'Author','UploadImage') html <form id="user_form" class="contact-form" method="post" action="{% url 'readingTime:ContactUs' %}" enctype="multipart/form-data"> <div class="contact-container"> <h2>Request To Add A Book</h2> {% csrf_token %} Bookd Id (ISBN) <input type="text" name="BookID" value="" size="30" /> <br /> Book Title <input type="text" name="BookTitle" value="" size="50" /> <br /> Author(Full Name) <input type="text" name="Author" value="" size="30" /> <br /> Book Cover(Optional)<input type="file" id="UploadImage" name="UploadImage"> <br/> <!-- Submit button--> <div> <button type="submit" class="submit-button">Send Request</button> </div> </div> </form> My form gets sent over to the admin side of the website but it appears with the form is not valid …