Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create a download api endpoint in djangorestframework for a csv file I am writing into after consuming data from a world weather online api's
I am consuming a weather api endpoint from HTTPS:https://api.worldweatheronline.com/premium/v1/weather.ashx and my views.py logic looks like this class HistoricalWeatherView(APIView): """Gets Historical Weather of a location""" def get(self, request, **kwargs): url = 'https://api.worldweatheronline.com/premium/v1/past-weather.ashx' param = request.query_params query_param = { 'key': 'my_api_key', 'q': param.get('location'), 'format': 'json', 'tp': 24, 'date': param.get('startdate'), 'enddate': param.get('enddate'), 'includelocation': 'yes' } weather_data = requests.get(url, params=query_param).json() output = len(weather_data['data']['weather']) final_weather = [] output_csv = 'historical_weather.csv' for result in range(output): final= { 'country': weather_data.get('data').get('nearest_area')[0].get('country')[0]['value'], 'areaName': weather_data.get('data').get('nearest_area')[0].get('areaName')[0]['value'], 'date': weather_data.get('data').get('weather')[result].get('date'), 'max_temperature': weather_data.get('data').get('weather')[result].get('maxtempC'), 'min_temperature': weather_data.get('data').get('weather')[result].get('mintempC'), 'indicator': weather_data.get('data').get('weather')[result].get('hourly')[0].get('weatherDesc')[0].get('value'), 'Humidity': weather_data.get('data').get('weather')[result].get('hourly')[0].get('humidity'), 'cloud_over': weather_data.get('data').get('weather')[result].get('hourly')[0].get('cloudcover'), 'windspeed': weather_data.get('data').get('weather')[result].get('hourly')[0].get('windspeedKmph'), 'precipitation': weather_data.get('data').get('weather')[result].get('hourly')[0].get('precipInches') } final_weather.append(final) df_weather = pd.DataFrame(final_weather) df_weather.to_csv(output_csv, index=False) return Response(final_weather, status=status.HTTP_200_OK) it generates the csv_file but I want to be able to create an endpoint where it can be downloaded to download folder localhost:8000/api/weather/history/download -
How to get value of {% url '...' %} programatically?
I would like to include the url of my DRF endpoint in the extra_context= field of my TemplateView so that I can pass it into my JS application in my template. I currently have it in my template, but it's just more convenient to store all the urls in the urls.py file. path('channel_bar', TemplateView.as_view( template_name='sales/bar_graph.html' extra_context={'dataUrl': reverse_lookup_drf_url('url-name')} ), name='sales.channel.bar'), and I don't know the Django name of the function reverse_lookup_drf_url(...) Tried searching "reverse lookup of template url tag programmatically" and a few permutations of it but didn't get any results. Anyone know the answer? I'm sure it's simple, just can't get a Google result. -
Allow end user to add / remove fields from model in Django
Please consider this situation: I've several clients on my website and each one can create employee from his dashboard. But each of them may want different fields in there form or user model. Example: Client_1 wants name, email, phone in there form Client_2 wants name, phone, address, and birth_date So from default form/model client should be able to remove unwanted fields and create his required fields. I Hope this can be done using Django or ContentTypes Please anyone knows then please provide detailed answer. It would be really helpfull. -
Django [Python], ImportError: cannot import name 'SimpleCookie' from partially initialized module 'django.http.cookie'
I have an M1 Apple Silicon Mac, and I am having some difficulty with my setup regarding Python version 3, specifically version 3.9.5. I also have Anaconda Navigator installed on my system. When I enter python3 --version into my zsh terminal, my Mac seems to point to the version of Python that is installed with Anaconda Navigator. I have included a screenshot of my VS Code instance where I was having an error trying to launch the default Django project, as well as some other files which contain my PATH variables. I have tried again and again to solve this issue, but I am more ore less stuck at this point. Any advice on how to configure my setup such that Django is available system-wide, with the latest version of Python, would be much appreciated. Scott My VS Code Django error -
I want to calculate timezone from lat/long in django in following format UTC +2 Central European summer time How can we do this? [closed]
I want to calculate timezone from lat/long in django in following format UTC +2 Central European summer time How can we do this? -
Django not using correct Postgres schema on Heroku
I have a Django app that I need to connect to a schema "new_schema" by default, rather than public. I've managed to get this working on my local instance by running CREATE SCHEMA new_schema; on the local database & then adding into my settings a database config like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=new_schema', }, 'NAME': 'database_name', 'USER': 'user_name', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': '5432', }, } But, when I deploy to Heroku & create the schema there, I can't get the app to point to the new schema. In my production settings file, I have DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) DATABASES['default']['OPTIONS']['options'] = '-c search_path=new_schema' in order to get the Heroku database url into the right config format, and then add in my schema to the options. But for some reason this doesn't work - instead any migrations get applied to public as do db queries. I can explicitly set the new_schema in the Postgres users search_path, but there are other servers that need different default schemas I have been going in circles trying to resolve this for ages, I don't know what I'm missing! I can' tell if this is a problem with … -
ModuleNotFoundError: No module named 'crispy_formsmain'
Please help me as I am new to Django and I am learning out of my curiosity. I tried to find the solution but couldn't. I have spent 2 days to find the appropriate solution. Please help. I cloned the repository from github and it gives me the error as follows: (env) C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 954, in _bootstrap_inner self.run() File `"C:\ProgramFiles\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 892, in run` self._target(*self._args, **self._kwargs) File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-`packages\django\core\management\commands\runserver.py", line 110, in inner_runautoreload.raise_last_exception()` File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crispy_formsmain' -
How to optimize django queries without hitting the database
I have a geojson file that contains more than 77 500 rows et 20 columns. With my actual view, it takes more than 30 minutes to upload the file. How can I optimize it without hitting frequently the database? class Edge(models.Model): #geometry = models.LineStringField() target = models.ForeignKey(Node, on_delete=models.CASCADE) source = models.ForeignKey(Node, on_delete=models.CASCADE) network = models.ForeignKey(RoadNetWork, on_delete=models.CASCADE) class Node(models.Model): network = models.ForeignKey(RoadNetWork, on_delete=models.CASCADE) node_id = models.BigIntegerField() name = models.CharField('Node Name', max_length=200) location = models.PointField() Here is theView : def upload_edge(request, pk): template = "networks/edge.html" roadnetwork = RoadNetWork.objects.get(id=pk) node_instance = Node.objects.filter( network_id=pk).select_related() list_edge_instance = [] if request.method == 'POST': form = EdgeForm(request.POST, request.FILES) if form.is_valid(): datafile = request.FILES['my_file'] objects = json.load(datafile) for object in objects['features']: objet_type = object['geometry']['type'] if objet_type == 'LineString': properties = object['properties'] target = properties.get('target') source = properties.get('source') try: target = Node.objects.get(node_id=target) source = Node.objects.get(node_id=source) node = Edge( target=target, source=source, network=roadnetwork) list_edge_instance.append(node) except ObjectDoesNotExist: pass Edge.objects.bulk_create(list_edge_instance) return redirect('home') else: form = EdgeForm() return render(request, template, {'form': form}) -
Filter api output by value stored in Join Table
I have many to many relationship between two models (First is origin country with list of countries and second is destination country with list of countries). I have created join table and I have set additional variable in it: class BorderStatus(models.Model): STATUS_CHOICES = [ ('OP', 'OPEN'), ('SEMI', 'CAUTION'), ('CLOSED', 'CLOSED') ] Country = models.ForeignKey(Country, on_delete=models.CASCADE) OpenDestination = models.ForeignKey(OpenDestination, on_delete=models.CASCADE) status = models.CharField(max_length=6, choices=STATUS_CHOICES, default='CLOSED') class Meta: unique_together = (('Country', 'OpenDestination')) def __str__(self): return str(self.Country) + ' and ' + str(self.OpenDestination) Now I set the view that it lists a country and all countries related with a status, like this: [ { "name": "Germany", "dest_country": [ { "id": 1, "name": "New Zealand", "status": "SEMI" }, { "id": 2, "name": "Watahia", "status": "CLOSED" }, { "id": 3, "name": "France", "status": "OP" } ] } ] Here is my serializer: class OpenDestinationSerializer(serializers.ModelSerializer): class Meta: model = OpenDestination fields = '__all__' class BorderStatusSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField(source='OpenDestination.id') name = serializers.ReadOnlyField(source='OpenDestination.name') class Meta: model = BorderStatus fields = ('id', 'name', 'status',) class CountrySerializer(serializers.ModelSerializer): """ Connect serializer so that it is seen in the api""" dest_country = BorderStatusSerializer(source='borderstatus_set', many=True) class Meta: model = Country fields = ('name', "dest_country") Now I want to add a filter that only … -
Is there Open-source ERP based on Django?
I am looking for Open source ERP for my father's manufacturing business. We have lost a lot in this covid-19 time and cant afford any expensive ERP. I am Django developer and I am looking for Django based ERP. Please help. Thanks. -
Models CharField Blank and Null
I have the following model : class Scenario(models.Model): title = models.CharField(max_length=30) subtitle = models.CharField(max_length=60) description = models.TextField(max_length=1000) image_url = models.ImageField(upload_to ='scenarios-pictures/%Y/%m/%d', default="", blank=False, null=False) slug = models.SlugField(null=True, unique=True) active = models.BooleanField(default=False) def __str__(self): return self.title If I try to create a scenario with empty values, it doesn't raise any exception. >>> from ihm_maquette.models import Scenario >>> scenario = Scenario.objects.create(title='', subtitle='', description='', image_url='', slug='') >>> scenario <Scenario: > >>> I don't get why, because I've read in the doc that blank and null are False by default. I've also read this explanation. Do you have any idea why the object is created? -
Django: Create QuerySet baed on number of one-to-many obejcts in DB
In Django, if I have two models One and Many with a one-to-many relationship how can I filter a Manager of One objects to create a QuerySet that only contains Ones that have one or more Manys? (This is a challenge proposed in the "Ideas for more tests" section of the Part 5 of the tutorial on the Django website) -
How to pass a parameter to a view with HTMX and Django?
I am trying to implement kind of a like-button with Django and htmx using django-htmx,but I do not know how how to pass the id as a parameter to my view in order to save the related item. # models.py class Item(models.Model): name = models.CharField() like = models.BooleanField(null=True, default=None) The (simplified) table shows items like this: id name like -- ----- ---- 1 Alpha None 2 Beta None The idea is by klicking e.g. on the first "None", Django should change the like-value for the first item in the database to "True" and this should be reflected in the table: id name like -- ----- ---- 1 Alpha True 2 Beta None The table is generated by a template like this: <table> {% for item in page_obj %} <tr> <td>{{ item.id }}</td> <td>{{ item.name }}</td> <td id="like-{{ item.id }}" hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}' hx-post="{% url 'save-like' %}?id={{ item.id }}" hx-target="#like-{{ item.id }}" hx-swap="outerHTML"> {{ item.like }} </td> </tr> {% endfor %} </table> With a click on "None", there is a request to the following function: #views.py def save_like(request): success = False if request.method == 'POST': item = Item.objects.filter(pk=request.POST['id']).first() item.like == True item.save() success = True if success: return HttpResponse('<td>True</td>>') else: … -
i want to print the data of input tag in views.py django
enter image description here enter image description here enter image description here enter image description herei have searched alot but couldnt find the bug.. there is no print of input tag information -
django html file load image like `{{post.image.url}}`
-models.py- class Post(models.Model): image = models.FileField(upload_to='note/static/note/') -html file- <img src={{note.image.url}} -error code- [14/May/2021 08:42:07] "GET / HTTP/1.1" 200 402 Not Found: /note/static/note/test.png [14/May/2021 08:42:07] "GET /note/static/note/test.png HTTP/1.1" 404 2357 Did I do anything wrong? -
How create csrf_token with js?
I create many different forms in a foreach loop but I can't send anyone because of the csrf_token. inputToken = _("input", null, newFormModiferReduction) //create <input> with null content, in newFormModiferReduction inputToken.setAttribute("name", "_tokenDelRed") inputToken.setAttribute("type", "hidden") inputToken.setAttribute("value", "{{ csrf_token() }}") When I did console.log of the value I get : {{ csrf_token() }} I tried without quotes, without braces, but it still doesn't work. I couldn't find a solution on the Internet. I tried with only one token in but it doesn't work without anny "error", I conclued that one form = one csrf_token I send these forms with AJAX so if there is another solution it could be find too -
Django fetch data from two table related to foreign ket
i want to fetch data from one model and related images means i want to get vehicle id and related to that vehiceid its related images based on F key relationship. #Model1 from django.db import models class VehicleAd(models.Model): vehiclename = models.CharField(max_length=50) #model 2 from django.db import models from .vehiclead import VehicleAd class Vehicleadimages(models.Model): vehiclead = models.ForeignKey(VehicleAd, on_delete=models.CASCADE,enter code hererelated_name="relatedvehiclead") image = models.ImageField(upload_to="images/vechileadimage") #views def viewVehiclead(request): vehiclead = VehicleAd.objects.all() vehicleadimages = Vehicleadimages.objects.all() print(vehiclead) context = { 'vehiclead':vehiclead, 'vehicleadimages': vehicleadimages } return render(request,'vehiclead/view.html',context) #html {% block body %} <div class="container bg-color-w shadow-lg custom-style-cont "> {% include "menu/top-menu.html" %} <div class="col-md-12 pd-arn2prc"> <div class="container"> <div class="row"> <div class="col-md-12 mx-auto"> <h1>h2</h1> <table> {% for v in vehiclead %} <a href="#">{{ v.vehicleadimages.image }}</a> {% endfor %} </table> </div> </div> </div> </div> </div> {% endblock body %} -
Is there a way to integrate django with react without using api?
I am trying to make a website using django and react (I dont know REST framework). And i have had some trouble communicating between front-end and back-end. I thought of a way to communicate but im not sure if it is a good one. Django has its own templating language so in index.html (of react app) can i do add a div that contains all the useful information like this and then further use that information to display on the page or there might be some security concerns. maybe something like this in index.html <div id='data'>{{ data }}</div> where data can be a JSON string. -
Performance: Database, Django, reverse lookup or direct?
I have 2 models. first contain 5000 objects. second contain 10M objects. class Follower(models.Model): username = models.CharField( _("username"), max_length=250, db_index=True) class Influencer(models.Model): username = models.CharField( _("username"), max_length=250, unique=True, null=False, blank=False, db_index=True) followers = models.ManyToManyField( "instagram_data.Follower", verbose_name=_("Followers")) I tried both options to get Followers objects out of influencer's usernames: influencer_choosen_by_user = ['nike', 'adidas'] if self.REVERSE_SCAN: qs = Follower.objects.filter( influencer__username__in=influencer_choosen_by_user) else: qs = Follower.objects.none() qs_influencer = Influencer.objects.filter(username__in=influencer_choosen_by_user) for influe in qs_influencer.iterator(): qs = qs | influe.followers.all() It seems that both results in same around 20 seconds .... are thay SQL the same ? I think the "REVERSE_SCAN" JOIN 10M with the middle table (manytomany middle table) while the second JOIN the 5K table with the middle table. am I right ? -
Importing Issue in Django
enter image description here it is not importing the DjA package in 19th line -
django.db.utils.IntegrityError: could not create unique index - DETAIL: Key (player)=(Lonergan) is duplicated. - without unique constraint in model
I did a few commits offline including updating the model a couple of times and later when all was deployed to production it was not possible to migrate the database. The error message is: django.db.utils.IntegrityError: could not create unique index - DETAIL: Key (player)=(Lonergan) is duplicated. It is over 100 players with a duplicate name in the table, the strange thing is that the field player was never set to be unique. Why is this happening? class Player(models.Model): player = models.CharField(max_length=50) team = models.ForeignKey(Team, related_name='players', on_delete=models.PROTECT) position = models.CharField(max_length=5) cost = models.FloatField() selection = models.FloatField() form = models.FloatField() points = models.IntegerField() lastgwscrape = models.DateTimeField(null=True) lastapiupdate = models.DateTimeField(null=True) currentgwdt = models.DateTimeField(null=True) apiid = models.IntegerField(null=True) The apiid field was previously defined as unique and it was removed as a test to make this migration work. class APIPlayerGW(models.Model): player = models.ForeignKey(Player, related_name='apigws', on_delete=models.CASCADE) gwid = models.IntegerField() points = models.IntegerField() minutesplayed = models.IntegerField() goalsscored = models.IntegerField() assists = models.IntegerField() cleansheets = models.IntegerField() goalsconceded = models.IntegerField() owngoals = models.IntegerField() penaltiessaved = models.IntegerField() penaltiesmissed = models.IntegerField() yellowcards = models.IntegerField() redcards = models.IntegerField() saves = models.IntegerField() bonuspoints = models.IntegerField() bonuspointsystem = models.IntegerField() influence = models.FloatField() creativity = models.FloatField() threat = models.FloatField() ictindex = models.FloatField() datetime = models.DateTimeField(default=timezone.now) … -
Why Ip in django honybot is None
I download honeypot using bib and added it in my url django project file, and I use it in my website that is production, I use nginx. and why Honeypot return <a href="?ip_address=None">None</a> -
CSS and JS of base django template not loading in other django templates which extends it
I made a base template for my django project called 'base.html' Now , I tried to extend this base template from 2 other templates called 'homepage.html' and 'product.html' the code for homepage.html is as follows: {% extends 'base.html' %} {% block content %} <!-- ========================= SECTION ========================= --> <section class="section-name padding-y-sm"> <div class="container"> <header class="section-heading"> <a href="#" class="btn btn-outline-primary float-right">See all</a> <h3 class="section-title">Popular products</h3> </header><!-- sect-heading --> <div class="row"> {% for product in newest_products %} <div class="col-md-3"> <div href="{% url 'product' product.category.slug product.slug %}" class="card card-product-grid"> <a href="{% url 'product' product.category.slug product.slug %}" class="img-wrap"> <img src="{{ product.get_thumbnail }}"> </a> <figcaption class="info-wrap"> <a href="{% url 'product' product.category.slug product.slug %}" class="title">{{ product.title }}</a> <div class="price mt-1">Rs {{ product.price }}</div> <!-- price-wrap.// --> </figcaption> </div> </div> <!-- col.// --> {% endfor %} // --> </div> <!-- row.// --> </div><!-- container // --> </section> <!-- ========================= SECTION END// ========================= --> {% endblock %} Now when I try to do the same in product.html page , that is , when i try to extending base.html from product.html too , the css and js is not working for some reason {% extends 'base.html' %} {% block content %} {% endblock %} What is the issue here … -
Django hosting on Cloudera applications: server not starting
I am trying to port a django web application from some server to cloudera "applications" and I was trying to make it work. I managed to do so with flask and fastapi applications, just the django framework is missing. My problem, when trying the base setup (https://docs.djangoproject.com/en/3.2/intro/tutorial01/), locally works like a charm but when I try to start up the server from an instance in cloudera, the server does not start and, more curiosuly, I get a weird output related to some package of the image I am spinning. (you can see I am bypassing the traditional runserver command on django because in the cloudera applications side I cannot run shells directly and also due to the fact that I would to tie it up with some environmental variable) below the manage.py import os import sys if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") from django.core.management import execute_from_command_line port_to_pass = 8000 args = ['name', 'runserver', '127.0.0.1:%d' % port_to_pass] execute_from_command_line(args) weird "print" (the instance I am spinning has got the exact same package versions installed locally): when I should be getting: any idea what might the problem be? -
How do I solve an OSError [Errno2] no such file or directory
I am trying to install Django but there was a problem the first time I installed it so I uninstalled it. When trying to install it again I got back a message saying that the requirement is already fulfilled in a certain folder then it brings up an error saying that packages could not be installed because there is no such folder or directory.