Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Concatenation in Django views error: this type has no size
I am trying to concatenate columns of strings & integer types in Django. the view is like below, def DList(request): d_list = List.objects.annotate( Address=Concat( 'addr1', 'addr2', 'addr3', 'City', 'State', Value(' - '), str('Pincode'), output_field=CharField(), ),).all() context = { 'lists': d_list } return render(request, 'CRUD/list.html', context) Issue arises when I try to insert a space or a symbol like hypen here. Runserver throws error as below, this type has no size What is the exact method to insert space or any symbols while concatenating column values in Django ? -
How do I save the value entered from a form in my template to be used in a different .py file in django
I've created a template with a form, and a view for that template. I assign the values entered by the user to a variable using a request.post, but how do I then call this variable with the value in a different .py file? -
Result not displaying in localhost Django
The result is not displaying in localhost, but it is displaying in http://127.0.0.1:8000/ Here is my code. I don't know why will that happen, I'm new to Django, so your solution would really help me to solve this. Thanks in advance! Index.html <script> $(document).ready(() => { $("input[id='image']").on('change', function (event) { let input = this; var reader = new FileReader(); reader.onload = function (e) { $('#banner').css('width', '350px') $('#banner').addClass('img-thumbnail') $('#banner').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); }) $('#process').click(() => { $('.buttons').hide() $('.loader').show() $('#title').html("Processing...") let image = $('#image').prop('files')[0] var data = image['name']; console.log(data) $.ajax({ url: "http://127.0.0.1:8000/api/", type: "POST", enctype: 'multipart/form-data', dataType: 'json', data: { image: data, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (xhr) { alert("Error while processing") }, error: function (xhr) { $('#title').html("Result") let result = (xhr.responseText).split("-"); let disease = result[0]; let accuracy = result[1]; $('.loader').hide() $('#disease').html("Result: " + disease) $('#graph').attr('src', '{% static "graph.png" %}') $('.result').show() } }) }) }) </script> Output using localhost Output using http://127.0.0.1:8000/ -
How to append Dictionary keys null values in a list?
I have a dictionary that has multiple keys and each key has multiple values in list format, if the keys have a Null value then the key should be appended to a list. here is my dictionary: {'XSTY':['21.01', '22.01'], 'STRY': ['31.01', None], 'SYER': ['34.21', None], 'HUHTY': [None, '45.22]} and I am using this approach to append the value of the keys whose values are null in the list final_dict = {'XSTY':['21.01', '22.01'], 'STRY': ['31.01', None], 'SYER': ['34.21', None], 'HUHTY': [None, '45.22]} data = [] for in in final_dict.keys(): if i == 'HUHTY': if len(final_dict[i]>0: data.append(i) print("Append Success") else: print("data did not append") the above code is appending the data for this key only HUHTY', but it should append the data for STRY,SYER,HUHTYall of these keys whose values areNone` inside the list. Any kind of help will be appreciated. I know that it's not appending the other keys due to this condition if i == 'HUHTY': please provide a better approach to do the same thing dynamically. -
python setup.py egg_info did not run successfully on deployment to heroku
I upgraded my pip version after deploying and hosting my website. Then i installed a new package pypaystack. when i attempt to push to heroku i get the error below. Project works fine in development stage. Collecting pypaystack==1.24 remote: Downloading pypaystack-1.24.tar.gz (5.4 kB) remote: Preparing metadata (setup.py): started remote: Preparing metadata (setup.py): finished with status 'error' remote: error: subprocess-exited-with-error remote: remote: × python setup.py egg_info did not run successfully. remote: │ exit code: 1 remote: ╰─> [12 lines of output] remote: Traceback (most recent call last): remote: File "<string>", line 2, in <module> remote: File "<pip-setuptools-caller>", line 34, in <module> remote: File "/tmp/pip-install-h6ay7jb3/pypaystack_2a3b97aa3d934da4b6c7a7d81a4a6ad2/setup.py", line 2, in <module> remote: from pypaystack import version remote: File "/tmp/pip-install-h6ay7jb3/pypaystack_2a3b97aa3d934da4b6c7a7d81a4a6ad2/pypaystack/__init__.py", line 3, in <module> remote: from .customers import Customer remote: File "/tmp/pip-install-h6ay7jb3/pypaystack_2a3b97aa3d934da4b6c7a7d81a4a6ad2/pypaystack/customers.py", line 1, in <module> remote: from .baseapi import BaseAPI remote: File "/tmp/pip-install-h6ay7jb3/pypaystack_2a3b97aa3d934da4b6c7a7d81a4a6ad2/pypaystack/baseapi.py", line 2, in <module> remote: import requests remote: ModuleNotFoundError: No module named 'requests' remote: [end of output] remote: remote: note: This error originates from a subprocess, and is likely not a problem with pip. remote: error: metadata-generation-failed remote: remote: × Encountered error while generating package metadata. remote: ╰─> See above for output. remote: remote: note: This is an issue with the … -
How to Create Blank Lower 48 Map in Django JS
I'm trying to create a blank map in a Django app (via a JS script) to fill in some data. I'm not looking for anything more than a div with statelines drawn. This tutorial attempts to do exactly that with d3. Unfortunately, it appears that the local file reference to a json file here is outdated and no longer works. All things considered, I gave it a shot with the modular -m flag from tghe command line. My code for loading the basemap and json file looks like this (the json file is stashed in the saem directory as the html that calls this) /* Functions for graphing Terra data on basemap Uses d3 library */ async function init() { let data = [0, 1, 2, 3, 4] // Set some specifications for the basemap let basemap_width = 960 let basemap_height = 500 // Build d3 projection // Scale in size to fit entire US let projection = d3.geo.albersUsa() .translate([basemap_width/2, basemap_height/2]) .scale([1000]); // Define path generator let path = d3.geo.path() .projection(projection) // Define scale and legend for basemap let color = d3.scale.linear() .range(["rgb(213,222,217)","rgb(69,173,168)","rgb(84,36,55)","rgb(217,91,67)"]); let legendText = ["Some range of values"]; // Create SVG element and append map to the SVG … -
Display .html file in iFrame uploaded as media file using Django
I'm looking to display an uploaded .html file in an iFrame on my template. I would rather NOT set it up as a url to visit in the urls.py file, I upload .html files from the admin panel to the media folder like so: model # Portfolio project overview model class Work(models.Model): html = models.FileField(upload_to="work_app/media/htmls/", null=True, blank=True) My first attempt to display it using this template.html code: {% extends "base.html" %} {% load static %} {% block page_content %} <h1>{{ work.title }}</h1> <div class="row"> <div class="col-md-8"> {% if work.html %} <iframe height="100%" width="100%" src="{{ 'work.html.url' }}"> </iframe> </div> </div> {% endblock %} ...looks like this: As you can see, the iFrame is displaying, but seems like it can't find the .html file (404). I saw in a few other posts that the html line should be: <iframe height="100%" width="100%" src="{% url 'work.html' %}"> </iframe> ..and to also add X_FRAME_OPTIONS = 'SAMEORIGIN' to your settings.py file, so I did both those, where I now get: What is this trying to tell me? What am I missing? UPDATE I have also tried: <iframe height="100%" width="100%" src="{{ work.html }}"> </iframe> to which I get another 404: -
Is there an 'offline Djangoproject' documentation for this one here https://www.djangoproject.com?
Can somebody please direct me to where I can or how can I download the 'offline Djangoproject' documentation like this one https://www.djangoproject.com but Pdf, ePub, etc? Your help will be much appreciated. Thanks in advance. -
Django: Passing parameters in url without using urls.py file
How can I pass parameters via URL without using the urls.py file? For example, instead of making a complicated url like example.com/page/12/red/dog/japan/spot or something like that, and then a corresponding entry in urls.py that will parse that url and direct it to a view, I want to simply get a url where I can freely add or remove parameters as needed similar to the ugly way example.com/page?id=12&color=red&animal=dog&country=Japan&name=spot Then in urls.py simply have something like path('page/<parameter_dictionary>', views.page, name='page' parameters='parameter_dictionary) If I have to use url patterns, how can I account for urls that have parameters that may or may not fit the pattern, such as sometimes http://example.com/page/12/red/dog/Japan/spot -> path('page/<int:id>/<str:color>/<str:animal>/<str:country>/<str:name>', views.page, name='page'), http://example.com/page/12/dog/red/Japan/-> path('page/<int:id>/<str:animal>/<str:color>/<str:country>', views.page, name='page') http://example.com/page/dog/red/Japan/-> path('page/<str:animal>/<str:color>/<str:country>', views.page, name='page') Not sure if I am being clear, so I will try to rephrase it. Basically, I want to be able to pass parameters in a non-defined order or non-defined number of parameters without worrying about it having to fit a set pattern in the urls.py. I would like to just have anything sent to http://example.com/page/ go to views.page(), and then be accessible by something like animal = request.GET['animal'] color = request.GET['color'] id = request.GET['id'] etc. so example.com/page?id=12&animal=dog&country=Japan&name=spot example.com/page?id=12&color=red&animal=dog&name=spot example.com/page?id=12&country=Japan&color=red&animal=dog&name=spot would all work … -
reconciling `static` folders in a React / Django / nginx project
I'm working on a rather large project with some colleagues who are making the Django half. I'm working on the React half (created with create-react-app, then ejected). Both projects live in the same repo, and are coordinated with nginx to look like one single project from the end user pov. The issue I'm running into is that both projects seem to insist on their static folders being named static, which is creating routing issues in the nginx config. Right now the React urls are being routed to one proxy-pass port and Django urls to a different port, which is otherwise working fine. What I'd like to do is either: rename the PUBLIC_APP var in the React half so all the React static files can be differentiated by urls of say, /react-project/static. So far I've been unable to find a way to do this that consistently renames all static files and it seems to be an outstanding React bug. set up nginx to route all /static/ routes to the Django proxy, and if not found there, then to the React proxy. I have very little nginx experience and can't seem to get the syntax to work. I want something like this: … -
issues in installing mysql client in django
when i try to install 'my SQL client' in Django I am facing this issue the error code showing the error code -
Why does Q notation in Django use bitwise operators?
As title: Why does Q() in Django use bitwise operators (| and &) and not logical operators OR and AND? Is there some built-in mapping on Django's end? -
Django and React : [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]
I am gettting the error: [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')], for submitting an image/file. I added the encryption type for the form 'multipart/form-data' same thing in Axios call too, but I still get the same error. I have a model like this: class MyModel(models.Model): img = models.ImageField(upload_to='media',blank=False) In views.py: class MyModelView(viewset.ModelViewSet): serializer_class = serializer.MyModelSerializer def post(self,request): data = serializer.MyModelSerializer(data=request.data) print(data.is_valid()) # this is false, means there is an error print(data.errors) #This one will display the error shown in the title of this question if data.is_valid(): img = data.data['img'] return Response('Success') return Response('Fail') In serializer.py: class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' In frontend side (React): function ImgComp(){ let [img,setImg] = useState({'image':''} let {image} = img function handleChange(e){ setImg( { ...img,[e.target.name]:e.target.value } ) } function submitForm(e){ e.preventDefault() axios.post('127.0.0.1:8000/mymodelurl/',img,{withCredentials:true,headers:{'Content-Type':'multipart/form-data'}}) return( <div> <form method='post' encType='multipart/form-data' onSubmit = {(e)=>submitForm(e)}> <input type='file' value={image} name='img' onChange={(e)=>handleChange(e)}/> </form> </div> } } If I debug the img I get something like: C:\\fakepath\\img.png -
How to write good code ? Is my code optimized?
Sometimes i wonder if i have written a lot of LOC to change my logic in to the programming. If my code is not that much optimized. To share those i have two pictures where i have to pass some context data in to Django Templates and I have had passed a lot of context data. And another picture contains the logic to have 13 months so that i can filter out my models QuerySet according to month. Because I need the data to create a chart in where i have to show the dynamic fluctuation in the data for past 12 months. My Question is :: Is the given codes optimize ? Is there any better way to write these out ? If exists please try to guide me Your help would mean a lot to me . Thanks enter image description here enter image description here -
How can I access the Django Rest Framework Response in Javascript?
I'm having trouble with something very simple: access the response body for the response of my own API endpoint. Here's my API View endpoint located at from rest_framework.request import Request as RESTRequest from rest_framework.response import Response from rest_framework.decorators import api_view import requests @api_view(['POST', 'GET']) def payment(request, *args, **kwargs): #not relevant code return "string" Here's my call in Javascript to the endpoint var c = await fetch('https://myurl.com/api/payment/', { method: 'POST', body: params, }) For some reason, I just cannot figure out how to actually access the data that is returned in the API View endpoint. I have a Response object, but nothing I try gets me the actual 'string' value I am returning in the logic for my API endpoint. When I go to the link for my api endpoint on my website, I do see the "string" and when I use Postman I see the "string", but I can't seem to get access to it in Javascript. Here's the response object in console.log: -
delete 2 duplicate database indexes created on marking a string as primary key in django with postgres
this very simple model created 3 separate, (and duplicate) indices in the postgres database. Is there any method to avoid duplicate indices in cases like these? or disable indexes of particular kind? My main concern is once the size of this table increases, all operations will begin to slow down as updating 3 indexes will have its cost (compute + storage). class SavedCard(Common): token = models.CharField( max_length=64, primary_key=True ) Indexes created: prefix_savedcard_token_6c141ea4_like prefix_savedcard_token_6c141ea4_uniq prefix_savedcard_token_6c141ea4_pk -
wagtail search_fields on snippet with foreign key
I have a snippet which is a proxy of one of my standard django models. search_fields works fine when filtering on standard fields, the problem is I can't seem to get foreign keys to work. This page has an example on the bottom that shows how to create searchable snippets: https://docs.wagtail.org/en/stable/topics/snippets.html The main model has a field called "day" which is a foreign key to a Day-table. A day has a calendar_year, which I would like to be able to filter on while searching in the wagtail snippets area. in the def str method I'm able to display the name in the list, the search is the problem here. Suggestions? @register_snippet class EventSnippet(index.Indexed, Event): # We make a proxy model just to be able to add to this file or potentially if we want custom methods on it. panels = [ FieldPanel('name'), ] search_fields = [ index.SearchField('day__calendar_year', partial_match=True), # This prompts an error index.SearchField('name', partial_match=True), ] class Meta: proxy = True def __str__(self): return f"{self.name} {self.day.calendar_year}" When running python manage.py update_index i get the following warning: EventSnippet.search_fields contains non-existent field 'day__calendar_year -
How to execute a Python function in HTML with parameters?
I am using Django and I have this function in a .py file Users = User.objects.all() def getCountData(idUser): idUser = int(idUser) for user in Users: if user.id == idUser: count = 0 if ... count += 1 ... return count in the html it is like this: <table> <thead> .... </thead> <tbody> {% for user in ... %} <tr> <td> {{ getCountData(user.id) }} <td> </tr> {% endfor %} </tbody> </table> but I get this error: Could not parse the remainder: '(user.id)' from 'getCountData(user.id)' I already tried with {% ... %} and I get the same The error is in passing the parameter, because without parameters it works (but I don't need that), how do I solve it? -
how can i make a <select> element in my form and model
ive wrote a code to practice html and python i used django to build a add music page its for uploading musics the whole form used models but i added another option today for tags this option is not in form.py nor models its just in html file so what will happen if i choose and press submit and also if i want to make same in model how should i do {% extends 'pages/base.html' %} {% block content %} <!DOCTYPE html> <head> <meta name="description" content="page of adding music"> <meta name="keywords" content="music,upload_music"> <title>adding music</title> </head> <body> <p>here you can upload music</p> <form action="{% url 'pages:add_music' %}" method='post' enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p}} <div> <h3 style="border:2px blue; color:blue;">tags:</h3> <select style="padding: 4px;" id="tags" name="tags" multiple required="required" size='6'> {% for tag in tags %} <option value="{{tag}}">{{tag}}</option> {% endfor %} </select><br> </div> <button type='submit' value="submit" style="margin: 20px; background-color: yellow; color: green;">add</button> </form> </body> {% endblock %} -
Django - how to make tags on a per user basis
on a Django project that uses django-taggit (https://pypi.org/project/django-taggit/) I would like to make tags on a per user basis, this way each user can define its own set of tags. I'm settings up the following model: # models.py from django.db import models from taggit.models import Tag from django.contrib.auth.models import User # Create your models here. class MyTag(Tag): """ You must make taggit.models.Tag an abstract model""" user = models.ForeignKey(User, related_name="to_tags", on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def save(self, args, kwargs): user = kwargs.pop('user') self.user = user super(MyTag, self).save(*args, **kwargs) then to manage I'd use a normal form ( in this case the tags are for a Photo model) # forms.py class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = ('name', 'artistic_name', 'description', 'tags', 'is_top', 'note') widgets = { 'description': forms.Textarea(attrs={'rows': 2}), 'note': forms.Textarea(attrs={'rows': 2}) } now the Question...how to I save the user in the MyTag model? I have to pass it to the form instance in the view doing something like: def photo_detail(request, photo_id): ... form = PhotoForm(request.POST or None, user=request.user) ... if request.method == 'POST': if form.is_valid(): form.save() ... first question...should I pass the user when I make the form instance, or when I call the save method...? … -
Different datetimes displayed in view and template in Django
When I display a datetime object in my template, the displayed result is a date very different from what I have in my database. Printing the datetime in the view for debbuging gives the same result as the dabatase. I'm guessing it gets parsed somewhere between the view and the rendered template which gives a different date but I cannot pinpoint exactly what's going on. I'm using DateTimeField in the database. Any help appreciated -
Converting picklefield from python2 to python3
Migrating from django==1.11.16 / python2 to django==4.0.5 / python3.8 and using django-picklefield in the database I'd like to convert the database to the new system. I'm looking for a solution how I could achieve this feat. A working way is: #on python2 venv: s = str(l.get_log()) #where get_log results the Pickled Object f = open('/tmp/somefile', 'wb') f.write(s) f.close() #on python3 venv: f = open('/tmp/somefile', 'rb') cn = f.read() l.log_list = eval(cn) Well, this is a working way, but because of eval can be very dangerous, and it uses both, the old and the new virtual env. I'm looking for a solution, which uses only one of the virtual environments for converting the picklefield rows in the database. -
Stream Django Output to HTML
I am trying to run python code and want to output that line by line to HTML page in Django Below is code I want to out to HTML page, I have integrated this in views.py(here named as as test_stream_script). I integrated this as when I was calling this code on separate cdoe.py file, I would not get at out on terminal until code was finished and then antire code would output to HTML. However integrating it in views.py I can see code being run on terminal. views.py: def ic_check_stream_test(request): global ssh_client print('connecting to the server ...') ssh_client = connect('10.9.60.70', 22, 'root', 'wh3nPO!42') print('\n') remote_connection = get_shell(ssh_client) print('connected to the server ...') ifconfig = send_command(remote_connection, 'ifconfig') print(ifconfig.decode()) process = send_command(remote_connection, 'ls -ltr /home/nms_logs/') print(process.decode()) send_command(remote_connection, '\n') print('\n') ping_test = send_command(remote_connection, 'ping 192.168.1.2 -c 20') print(ping_test.decode()) send_command(remote_connection, '\n') print('\n') close_session_bc() return render(request, 'base_app/test_script_2.html') urls.py: from django.urls import path, include, re_path from base_app import base_app_views, test_stream_script app_name = 'base_app' urlpatterns = [ re_path(r'^home/', base_app_views.home, name='home'), re_path(r'^ic_check_stream_home/', test_stream_script.test_home3, name='test_home3'), re_path(r'^ic_check_stream_test/', test_stream_script.ic_check_stream_test, name='ic_check_stream_test'), ] HTML page: <div class= "container"> <div class="jumbotron"> <h1>IC Stream Test Scripts</h1> </div> </div> <form action="/ic_check_stream_test/" method="post"> {% csrf_token %} Enter BC IP Address: <input type="text" name="param" required><br><br> <input type="submit" value="Exceute … -
How do I get rid of this object / Dictionary while retaining the data i've scrapped?
i'm web scrapping a site for data using beautifulsoup4 that i can use in a school django project, and i'm not sure how to be specific to the data i want without calling an unwanted object. I've failed to get rid of it. import requests from bs4 import BeautifulSoup headers = {'User-agent': 'Mozilla/5.0 (Windows 10; Win64; x64; rv:101.0.1) Gecko/20100101 Firefox/101.0.1'} url = "https://elitejobstoday.com/job-category/education-jobs-in-uganda/" r = requests.get(url, headers = headers) c = r.content soup = BeautifulSoup(c, "html.parser") table = soup.find("div", attrs={"article": "loadmore-item"}) def jobScan(link): the_job = {} job = requests.get(url, headers = headers) jobC = job.content jobSoup = BeautifulSoup(jobC, "html.parser") name = jobSoup.find("h3", attrs={"class": "loop-item-title"}) title = name.a.text the_job['title'] = title print('The job is: {}'.format(title)) print(the_job) return the_job jobScan(table) this is the result it fetches PS C:\Users\MUHUMUZA IVAN\Desktop\JobPortal> py absa.py The job is: 25 Credit Officers (Group lending) at ENCOT Microfinance Ltd {'urlLink': 'https://elitejobstoday.com/job-category/education-jobs-in-uganda/', 'title': '25 Credit Officers (Group lending) at ENCOT Microfinance Ltd'} I want to be able to retain "The job is: 25 Credit Officers (Group lending) at ENCOT Microfinance Ltd" and drop "{'urlLink': 'https://elitejobstoday.com/job-category/education-jobs-in-uganda/', 'title': '25 Credit Officers (Group lending) at ENCOT Microfinance Ltd'}" -
How to identify that requests are coming from my own django website?
I'm trying to use the django rest framework to identify when an API Request is coming from my own website (in order to send an error to these requests). views.py from django.shortcuts import render from django.http import JsonResponse from rest_framework.request import Request as RESTRequest def is_rest_request(request): return isinstance(request, RESTRequest) def payment(request, *args, **kwargs): if is_rest_request(request): return JsonResponse({"result": 502}) else: return JsonResponse({"result": 209}) However, when I make the following request from an online python compiler: import requests x = requests.get('https://url.com/api/payment') print(x.text) I get this output: {"result": 209}, when I should be getting {"result": 502} Any reasons why?