Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Render template context data referenced from hardcoded HTML in Django model
I have a Django app which is a news service. I have a basic html page which renders a single article. Up until now, every article had a standard format, Image, Author, and text content. Now I am making an update to allow articles to have multiple images between various paragraphs of the article text. Currently, my HTML page to render a single article gets its data injected via a context object which contains the following Article model: class Article(models.Model): title = models.TextField() author = models.ForeignKey(Author, on_delete=models.CASCADE) content = models.TextField() date = models.DateField(default=now) image = models.ImageField(storage=MediaStorage(), default='') external_source = models.TextField(null=True, blank=True) featured = models.BooleanField(null=False, blank=True) slug = models.SlugField() album = models.OneToOneField(Album, related_name='album', on_delete=models.CASCADE, null=True, blank=True) Within the HTML template, I display the content with the following code <p> {{ article.content|safe }} </p> Since I want to embed the album images within the text, I am attempting to put HTML code inside the content TextField like the following: Some random article text followed by and image... <img class="img-responsive single_article_image" src="{{album.image.url}}"> Some more random article text The problem is that the src reference to album.image does not resolve from the injected context and no image is rendered. The reason why I cannot … -
How can i use multiple request.query_params in conditions using Django
Here i am using request.query_params to take the parameter in API through URL but currently i am trying to use multiple params as per conditions like: here in one condition i am taking field, page, rows and in one condition i am taking page and rows and so on but it is only considering 1st condition and ignoring the remaining conditions. class SampleView(APIView): def get(self, request): if request.query_params['page'] and request.query_params['rows']: # Pagination page = int(request.query_params['page']) rows = int(request.query_params['rows']) val1 = rows*(page-1) val2 = (val1+rows) qry = DeviceControlPolicy.objects.all()[val1:val2] qry_length = DeviceControlPolicy.objects.count() serializer = DeviceControlPolicySerializer(qry, many=True).data data = { 'count': qry_length, 'data': serializer } return Response(data) elif request.query_params['field'] and request.query_params['page'] and request.query_params['rows']: page = int(request.query_params['page']) rows = int(request.query_params['rows']) val1 = rows * (page - 1) val2 = (val1 + rows) field = request.query_params['field'] qry = DeviceControlPolicy.objects.all().order_by(field).values()[val1:val2] qry_length = DeviceControlPolicy.objects.count() print(qry_length) serializer = DeviceControlPolicySerializer(qry, many=True).data data = { 'count': qry_length, 'data': serializer } return Response(data) Please help me out how can i do this and can use multiple conditions using different number of params. -
RuntimeError:doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I'm getting this error while i am using my own AUTHENTICATION_BACKENDS from django.contrib.auth.backends import ModelBackend import re from tainfo.apps.users.models import User def get_user_by_account(account): try: if re.match(r'1[3-9]\d{9}',account): user = User.objects.get(mobile=account) else: user = User.objects.get(username=account) return user except User.DoesNotExist: return None class UsernameMobileAuthBackend(ModelBackend): def authenticate(self,request,username=None,password=None,**kwargs): user = get_user_by_account(username) if user and user.check_password(password) and user.is_active: return user I put this in my devsettings.py: AUTHENTICATION_BACKENDS = ['users.utils.UsernameMobileAuthBackend',] if i delete this from settings,then this error will gone,but i that case i won't be able to use my own auth backends. any idea what i have done wrong? thanks -
Access to associated objects
I'm coming from Java and new to python / django. So may be my question is silly ... I have one class Parent which contains an association with a class Child. class Parent(models.Model): pass class Child(models.Model): value = models.DecimalField(decimal_places=2, max_digits=12,default=0.0); parent = models.ForeignKey(Parent, on_delete=models.CASCADE, null=True, related_name='children') Parent refers to its 'Childs' through the related name 'children'. At Run time it works well, but at design time, it isn't reachable from the declaration of the class Parent. If I want the parent to get a summarized value of its children, the best option I found is to first get the set of children and then to summarize from it class Parent(models.Model): def total_value(self): return float(Child.objects.filter(parent=self).aggregate(Sum('value'))['value__sum']) or 0.00 pass Do you know if there is a better way to do this? Can't we imagine something like: children.aggregate(Sum('value')) In other words: is it possible to directly access the children from the Parent (at design time) without making a query ? Thanks in advance for your support on this. -
What is the best option for an on demand service applications backend?
I am a little confused about what would be the best backend solution for an on demand service app startup with small expected active daily users <1000. I am looking for the most cost effective over long term option, in case active users exploded. 1- Django 2- Firebase 3- NodeJS with MongoDB -
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...? …