Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add multiple contents in google maps info windows in django with javascript
I am using the Django framework. I created multiple markers and info windows with images in it on Google Maps. It works well so far but some users have multiple items and on the map just one item is shown. I want these items to be seen at same info window or indifferent. models.py class Customer (models.Model): user= models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True) latitude = models.CharField(verbose_name="Latitude", max_length=50, null=True, blank=True) longitude = models.CharField(verbose_name="Longitude", max_length=50, null=True, blank=True) def __str__(self): return self.name class Product(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) description = models.CharField(max_length=200, null=True, blank=True) item_pic = models.ImageField( null=True) map js code inside the html function initMap() { var markers2=[] {% for product in products%} var lats = '{{ product.customer.latitude }}' var lats2 = parseFloat(lats) var lg = '{{ product.customer.longitude }}' var lg2 = parseFloat(lg) var mark = {coord:{lat:lats2,lng:lg2}, content : "<div >'<div class ='box small' style='float:left'; ><a href= {% url 'indexitem' product.id %} style = 'font-size:16px; text-decoration:none; color:black'><img id='surf1' src='static/images/{{product.item_pic}}'><br></div><div style='float:right; padding: 10px; font-size:14; '><b>{{product.name}}</b><br><b>${{product.price|floatformat:2}}</b> </div>", content2 : "<div >'<div class ='box small' style='float:left'; ><a href= {% url 'indexitem' product.id %} style = 'font-size:16px; text-decoration:none; color:black'><img id='surf1' src='static/images/{{product.item_pic}}'><br></div><div style='float:right; padding: 10px; font-size:14; '><b>{{product.name}}</b><br><b>${{product.price|floatformat:2}}</b> </div>", … -
django rest framework override save() method
When I override the save() method, the create() method is called inside, but when I add a read-only field uuid, the field is not serialized. serializer.py class AwsUploadFileSerializer(serializers.ModelSerializer): extract_file_name = serializers.CharField(source='extract_file.name', read_only=True) class Meta: model = ExtractAWSFile fields = [ 'uuid', 'extract_file', 'extract_file_name' ] extra_kwargs = { 'extract_file': {'write_only': True} } def save(self, **kwargs): instance: ExtractAWSFile = super().create(self.validated_data) res = upload_file_to_aws(instance.extract_file.path) if not res: instance.extract_file.delete() instance.delete() return instance response { "extract_file_name": "tets3.jpg" } So I'm trying to call the save() method of the parent class so that the uuid field can be serialized, but there is something wrong with the file name field I wrote earlier and it will take the path with it instead of just displaying the name. serializer.py class AwsUploadFileSerializer(serializers.ModelSerializer): extract_file_name = serializers.CharField(source='extract_file.name', read_only=True) class Meta: model = ExtractAWSFile fields = [ 'uuid', 'extract_file', 'extract_file_name' ] extra_kwargs = { 'extract_file': {'write_only': True} } def save(self, **kwargs): instance = super().save(**kwargs) res = upload_file_to_aws(instance.extract_file.path) if not res: instance.extract_file.delete() instance.delete() return instance response { "uuid": "c4aea74e-3748-4c05-8d6c-2413b1eebcc6", "extract_file_name": "extractAWS/2022/10/08/tets3.jpg" } Why is that? I'm wondering what I should do after save() to properly display the uuid field -
Ajax addEventListener stops working after first click
I am trying to populate a calendar with Ajax with Django backend. The code works just fine when I load the page and click id="wp-calendar-nav-next" and it populates the calendar as per my requirement. However it doesn't work after the first click. How do I recode it to make sure id="wp-calendar-nav-next" works constantly. I am trying to fix this before coding id="wp-calendar-nav-prev". <div class="widget-calendar-container " id="django-calendar"> <div class="calendar-header"> <div class="wp-calendar-nav-prev" id="wp-calendar-nav-prev"> <a>Jan</a> </div> <div class="calendar-title" id="cur_mon">{{ activity_month|title }}</div> <div class="wp-calendar-nav-next" id="wp-calendar-nav-next"> <a>Mar</a> </div> </div> <table id="wp-calendar" class="wp-calendar-table"> <thead> <tr> <th scope="col" title="Sunday">Sun</th> <th scope="col" title="Monday">Mon</th> <th scope="col" title="Tuesday">Tue</th> <th scope="col" title="Wednesday">Wed</th> <th scope="col" title="Thursday">Thu</th> <th scope="col" title="Friday">Fri</th> <th scope="col" title="Saturday">Sat</th> </tr> </thead> <tbody id="ajax-calendar"> <tr> {% for day in c_monthdays %} <td {% if day == activity_day %} class="calendar-viewing" {% endif %}> <div class="calendar-day-content"> {% if day == 0 %} {% else %} <a href="{% url 'calendermonthday' activity_month day %}" class="ga-calendar-day-link"> {{ day }} {% endif %} </a> </div> </td> {% if forloop.last %} </tr> {% elif forloop.counter|divisibleby:"7" %} </tr> <tr> {% endif %} {% endfor %} </tbody> </table> </div> Below is the script: <script> const loadBtnNext = document.getElementById('wp-calendar-nav-next'); function load_next_month() { var current_month = document.getElementById('cur_mon').textContent; const content_container = document.getElementById("django-calendar"); … -
drf_yasg manual parameters configuration
I am working with drf_yasg for the very first time and I am curious to know what does IN_QUERY and the other options provided by OPENAPI do. I can't find an explanation for the purpose of these options in the documentation. -
How to retrieve data from a table and display it with Python and Django in an html file?
for the purposes of an introductory course in python, Django and Postgresql, I am looking for the best way to retrieve table data and display it in a structured way in an html file with Django and python as a tool and language. Thank you all for your responses -
Google Registration, jwt staying logged in
I just added a feature to be able to register with Google. For security reasons I added a field in the db that is false if the user is registered the usal way(Username & PW) and true if he is registered with google. class CustomUser(AbstractUser): objects = UserManager() REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' username = models.CharField(max_length=40, unique=False,null=True, blank=True) email = models.EmailField(_('email address'), unique=True) profile_image = models.ImageField(null=True,blank=True,default = "users.png",upload_to='',) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False) telephone = models.CharField(blank=True, max_length=20, null=True) email_is_verified = models.BooleanField(default = False, null=False, blank = False) currentVerificationToken = models.CharField(max_length = 6, default="000000") withGoogleRegistered = models.BooleanField(default = False) def __str__(self): return self.email So if you try to login the usal way but the email adress is bounded to an google registered account, you wont be able to. If you try to login with a usal way bounded email adress, but its connected to a google bounded account , you wont be able to. So, I made this in order to seperate betweena accounts with a password and accounts without a password... But there is a little problem now. In Order to obtain an refresh token (JWT) I have to give a username and a password, otherwise … -
How to use a raw query in Django that uses an external database as well as a Django model
I have an external database with source data. (Microsoft db) How can I query this database and do an inner join on a Django model? I have two connections set up in settings.py This way I can acces the external database like this: "with connection['externalDB'].cursor() as c:" This external db has millions of records. I want run a query and then save that model into another Django model. SELECT product ,client FROM [external db] INNER JOIN [django model] WHERE client = 'foo' What would be the best way to approach this? -
How to perform eth contract transaction in Django using web3.py and Metamask
Trying to build a Dapp using Django, till now completed below steps. Deployed a simple lottery contract on test net, contract address is 0xD5d56C139848A0E55DC5C616D04a0CeD98D8BeA3 (can be seen at https://sepolia.etherscan.io/) Using web3.py I can connect to this contract and call the functions. I have created a simple webapp which ask user to connect to its Metamask wallet. I am using JS to load the Metamask wallet in the browser. When user click on connect wallet Metamask extension loads in the browser. Once user gets connected I can read the address of the connected user address. Next step is user will click on enter lottery button, after that Metamask should popup to sign the transaction. The Problem is I want to use the web3.py in my Django view to call my contract function which will allow user to enter in to the lottery game, but how can I call Metamask from Django view to ask user to sign transaction as it is browser extension. -
Filter django admin list with text input
Based on django ModelAdmin document for filterize list data, exist some class in admin that making filters, like DateFieldListFilter, ChoicesFieldListFilter and etc, But dosent exist any class for text input field. I need to use several text input fields for filter my model list data in admin page. What can i do? -
DRF SearchFilter Datetimefield Unsupported lookup 'gte'
I have a field timestamp which is a DateTime field when I'm filtering by this field in the shell it works fine with '__gte' or '__lte' $ python manage.py shell >>> from inventory.models import Order >>> Order.objects.filter(timestamp__date__gte=('2022-06-06')) >>> <QuerySet [<Order: ID: 22>, <Order_id: 27>, ....] but when I use SearchFilter it raises an error django.core.exceptions.FieldError: Unsupported lookup 'gte' for DateField or join on the field not permitted, perhaps you meant gte or gt or lte? models.py class Order(models.Model): timestamp = models.DateTimeField(auto_now_add=True) views.py from rest_framework.generics import ListAPIView from rest_framework import filters class Invoices(ListAPIView): serializer_class = InvoicesSerializer permission_classes = [IsAuthenticated, CustomModelPermissions] queryset = serializer_class.Meta.model.objects.all() filter_backends = [filters.SearchFilter] search_fields = ['timestamp__date__gte'] -
Django in python
**i want to making a site with django but i recive this error :excepted 'endblock', did you forget to register or load this tag? ** **Invalid block: ** -
How to return a string expression for order_by args in django queryset?
Let say i want to do this in the views of a Django project order_by_query = request.query_params.get("order_by", "") order_by_expression = compile_ob(order_by_query) qs = SomeModel.objects.all().order_by(order_by_expression) I expect the order_by_query to be a string like field1,-field2 so I will write a function like def compile_ob(expression: str) -> ??: my questions are: what should i write inside the compile_ob function? what should i return as type? Thank you -
why do i need to restart my docker container to see changes in django views.py file on windows
Why do I have to restart my docker container every time I make a change in my Django python files? I'm running a Django app via Docker and it seems any changes I make in my Views(and possibly elsewhere) are not reflected until I restart my container. For example, if I log an output to the terminal or make changes, then refresh, there's no change. If I restart my container and then refresh, I get the result I would expect. -
Should I use CSRF when setting JWT token using cookie in Django?
I am developing an API back end with Django, that uses JWT tokens for authentication. After reading numerous articles on JWT authentication and security, I concluded that it is best to store the JWT refresh token using an HttpOnly cookie. I also read that when using setting cookies with the Django Rest Framework, you should use CSRF protection. So... 1. Should I set a CSRF cookie when setting the JWT refresh token? I implemented my own methods for setting the refresh_token cookie upon successful requests to the LoginView and RefreshView. If I do need to set the CSRF cookie, should I also set it on those same views and then validate it when the refresh token is used, for example, when refreshing and logging out? Also... 2. How should I store the JWT access token? I have a React front end and, at the moment, I am storing the access tokens in localStorage. Would it be better if I were to store the token in a global state, for example using Redux? Forgive me if I don't know what I am talking about - my front-end knowledge is very limited. -
DRF Response isn't working with class based views in Django
I am converting my function-based views to class-based views. Following the official documentation, I was getting errors using the Response imported from rest_framework. When using HttpResponse it's working fine. The error I am getting with Response is: .accepted_renderer not set on Response This is my view: def get(self, request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) What could be the reason for this? -
Docker selenium not redirecting on another page in django test
I have some issue with docker selenium. For example, I have tried it on local selenium using operadriver, so redirecting to another page, after submit form, was working.I want to see this result also in django selenium test, but I've just get selenium.common.exceptions.TimeoutException: Message: in waiting when url will change. This is my test code import os import socket import shutil # from pyvirtualdisplay import Display from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options from django.test import LiveServerTestCase from django.conf import settings # Create your tests here. class LandFormTest(LiveServerTestCase): host = socket.gethostbyname(socket.gethostname()) def setUp(cls): selenium_url = 'http://selenium:4444/wd/hub' options = Options() options.add_argument('--no-sandbox') options.add_argument('--headless') options.add_argument("--disable-dev-shm-usage") options.add_argument("--ignore-certificate-errors") # options.add_argument("My user agent") options.add_argument(f"window-size=1920,1080") cls.driver = webdriver.Remote( command_executor=selenium_url, desired_capabilities=DesiredCapabilities.CHROME, options=options ) def test_form(self): try: driver = self.driver domain = self.live_server_url.split('//')[1].split(':')[0] if not settings.BASE_DIR.joinpath(f'templates/lands/{domain}').is_dir(): src = f'templates/lands/quantum.localhost' dest = f'templates/lands/{domain}' shutil.copytree(src, dest) driver.get(f'{self.live_server_url}/api/v1/test/?ai=2&gi=5') user_firstname = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.NAME, "firstname")) ) current_url = driver.current_url user_firstname = driver.find_element(By.NAME, 'firstname') user_lastname = driver.find_element(By.NAME, 'lastname') user_email = driver.find_element(By.NAME, 'email') user_phone = driver.find_element(By.NAME, 'phone') user_firstname.send_keys('test') user_lastname.send_keys('test') user_email.send_keys('test@gmail.com') user_phone.send_keys('+(846)411-36-00') user_phone.submit() WebDriverWait(driver, 10).until(EC.url_changes(current_url)) print(driver.current_url) print(driver.page_source) assert 'Hello World' in driver.page_source except … -
Permission based media server
I wanna build web based file/media(can be any type such as .mp4, .something) server using Django and JWT will handle the authorization. As normally, all media files are publicly accessible if we copy paste absolute path. How can setup in a way when only authorised user can access that specific file/media? -
How to Deploy Django Serving React App on AWS Elastic Beanstalk?
After quite a bit of debugging, I finally managed to successfully deploy the Django portion of my full-stack app on AWS Elastic Beanstalk. Here is the .config file in .ebextensions that I'm using: option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "waifu_database.settings" PYTHONPATH: "/opt/python/current/app/waifu_database:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: waifu_database.wsgi:application However, I still have the React portion to deploy. I know that it would probably be easier to separate the two, but is there a way I can install all the packages using npm and deploy it with the Django backend? I've already tried this but it just gave me a "Failed to deploy application" error. Here is my file directory: waifu_database |- .ebextensions |- .elasticbeanstalk |- api |- frontend |- node_modules/ |- src/ |- static/ |- templates/ |- package.json |- waifu_database |- asgi.py |- settings.py |- urls.py |- wsgi.py |- manage.py |- requirements.txt Here is my package.json file: { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack --mode production --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.19.3", "@babel/preset-env": "^7.19.3", "@babel/preset-react": "^7.18.6", "babel-loader": "^8.2.5", "react": "^18.2.0", "react-dom": "^18.2.0", "webpack": "^5.74.0", "webpack-cli": "^4.10.0" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.18.6", … -
What is the proper way to set third party urls in settings?
I am calling some third party apis from my django view. What will be the best configuration for setting the third party api credentials ? With this current config i am only setting server on the env. What would be the best approach get all the key and url from env only or below like this ? settings.py server = os.getenv("server", "staging") if server == "production" third_party_api_key = "some key" url = "some_url" elif server == "staging": third_party_api_key = "some key" url = "some_url" else: third_party_api_key = "some key" url = "some_url" -
social network developer's image compression
I am basically developing a social network to share images using Django and one of my issues is how to compress images all for the same size of 470x470 -
Django: Loop / iterate nested list with multiple sublevels
Here are my snippets: models.py class Item(models.Model): name = models.CharField('Name', max_length=50, unique=True) toplevel = models.BooleanField('Top level item', default=False) order = models.IntegerField('Order number', blank=True, null=True) #only if top level is true, determines the top level order class Hierarchy(models.Model): mainitem = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='mainitem') subitem = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='subitem') order = models.IntegerField('Order number', default=0) #determines the order of the subitems under the mainitem views.py def items_view(request, *args, **kwargs): items = Item.objects.all() toplevelitems = Item.objects.filter(toplevel=True) sublevelitems = Item.objects.filter(toplevel=False) context = { 'items':items, 'toplevelitems':toplevelitems, 'sublevelitems':sublevelitems, } return render(request, "itemlist.html", context) itemlist.html {% if items %} <ul class="list-group list-group-flush"> {% for toplevelitem in toplevelitems %} <li class="list-group-item">{{ toplevelitem.order }} {{ toplevelitem.name }}</li> {% for sublevelitem in sublevelitems %} <ul class="list-group list-group-flush"> <li class="list-group-item">{{ sublevelitem.name }}</li> </ul> {% endfor %} {% endfor %} </ul> {% else %} <p>No created items</p> {% endif %} So what I am trying to built with these is a hierarchy of items that will be itereted for the client in a nested list. What I cannot figure out is how to loop through all the levels of the hierarchy and place them under the right upper level. Here is what I am going for: Item 1 (top level item) Item 1.1 … -
dango app, images don't show up after heroku restart even my images are on cloudinary
I am uploading my images to cloudinary. This is a test project. After 24 hours The images don't show on django-website. Host is heroku. #settings .py changes STATIC_ROOT = BASE_DIR / 'staticfiles' CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'here is my cl name', 'API_KEY': 'here is my api key', 'API_SECRET': 'here is my api secret', } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' # models.py changes image = models.ImageField(upload_to='test_project_cloudinary/', null=True) #views.py if request.method == "POST": form = ImageForm(request.POST, request.FILES) if form.is_valid(): print("form validated") form.save() return redirect("home") else: print("form not validating") -
Conditionally bulk_create or bulk_update model instance fields based on the conditional equality of two foreign key related fields in Django
I'm trying to bulk_create or bulk_update instances of a model Matchup, where two of its fields are dependent on the equality or lack thereof of two of its related fields' reverse relationships. The Matchup has both a home_team and away_team, both of which are ForeignKey fields. There's are also is_divisional and is_conference fields to denote whether the matchup is between teams in the same division or conference. class Matchup(models.Model): home_team = models.ForeignKey( "teams.Team", on_delete=models.CASCADE, related_name="home_matchups", ) away_team = models.ForeignKey( "teams.Team", on_delete=models.CASCADE, related_name="away_matchups", ) is_divisional = models.BooleanField(default=False) is_conference = models.BooleanField(default=False) The Team model also has two ForeignKey fields, conference and division. class Team(models.Model): conference = models.ForeignKey( "leagues.Conference", on_delete=models.CASCADE, related_name="teams", ) division = models.ForeignKey( "leagues.Division", on_delete=models.CASCADE, related_name="teams", ) So the goal here is to check whether the Matchup.home_team and Matchup.away_team belong to the same conference or division. If so, is_conference/is_divisional respectively should be True. Here's what I initially had. It works, but leads to hundreds of duplicate queries. I perform this bulk_update after all the objects are created in bulk. for matchup in matchup_objs: if matchup.home_team.division == matchup.away_team.division: matchup.is_divisional = True if matchup.home_team.conference == matchup.away_team.conference: matchup.is_conference = True Matchup.objects.bulk_update(matchup_objs, ["is_divisional", "is_conference"]) In an attempt to reduce the duplicate queries, I tried using … -
Calculate the total amount of the cart in django rest framework
I'm new in django,I need calculate cart summa and I have these models: class Customer(Base): name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100, blank=True, null=True) comments = models.CharField(max_length=255, blank=True, null=True) class Cart(Base): user = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="cart") cart_number = models.CharField(max_length=500, default=increment_cart_number, null=True, blank=True) total_summa = models.FloatField() is_saved = models.BooleanField(default=False) class Item(Base): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product') product_price = models.FloatField() quantity = models.IntegerField(default=1) I used generics view, Can i calculate cart summa like this Bread 3x6000 = 18000 Milk 2x500 = 10000 Total_Summa = 28000 Could you help me please? -
Not able to longin to django admin panel after creating custom super user
Hey guys I tried my best but I am not able to log in to the django admin panel with my custom made user model. I did do all the things I can, I also did the authentication for the email and the rest but I still am not able to log into the django admin panel it keeps saying this "Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive." I tried and checked my password probably a hundred times now but still I won't let me log in. Can someone please help me with this, it would be the biggest help ever. I have been stuck here for like a month now I have pasted all the code that I did below:- models.py:- from django.db import models import uuid from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.utils.translation import gettext_lazy as _ class CustomAccountManager(BaseUserManager): def create_user(self, first_name, last_name, phone_number, email, password, **other_fields): if not email: raise ValueError(_('You must provie an email address')) if not first_name: raise ValueError(_('You must provide a first name')) if not last_name: raise ValueError(_('You must provide a last name')) email = self.normalize_email(email) user = …