Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Capturing An Image From The Computer's Camera And Saving It
I am trying to capture an image of someone with the computer's camera, save it as a PNG image, and then send it to a view function in the Django framework. I have found some source code for this at the following link: https://www.studytonight.com/post/capture-photo-using-webcam-in-javascript The following source code is what I have so far: <!doctype html> <head> <style> #video { border: 1px solid black; width: 320px; height: 240px; } #photo { border: 1px solid black; width: 320px; height: 240px; } #canvas { display: none; } .camera { width: 340px; display: inline-block; } .output { width: 340px; display: inline-block; } #startbutton { display: block; position: relative; margin-left: auto; margin-right: auto; bottom: 36px; padding: 5px; background-color: #6a67ce; border: 1px solid rgba(255, 255, 255, 0.7); font-size: 14px; color: rgba(255, 255, 255, 1.0); cursor: pointer; } .contentarea { font-size: 16px; font-family: Arial; text-align: center; } </style> <!--The title of the HTML document.--> <title>Facial Image Recognition</title> </head> <body> <div class="contentarea"> <h1>Facial Image Recognition</h1> <div class="camera"> <video id="video">Video stream not available.</video> </div> <!--An id on a <button> tag assigns an identifier to the button. The id allows JavaScript to easily access the <button> element and manipulate it. When a user clicks on the "Capture Image" button, … -
Get local variables of called function before return in python
I am using Django 2.2, and I have the following view (reduced version): @method_decorator(log_request(settings.LOGGER_PAYMENT_TRANSACTION), "post") class UltimateOrderPaymentView(SettingsIncludeMixin, APIView, PayTRMixin): def post(self, request, *args, **kwargs): serializer = UltimatePayOrderSerializer(data=request.data) serializer.is_valid(raise_exception=True) orders = Order.objects.filter( id__in=serializer.validated_data["order_ids"], is_paid=False, status_id=Status.objects.order_statuses(level="base").first().id, user=request.user, ).select_for_update() with transaction.atomic(): ids = list(orders.values_list("id", flat=True)) if not ids: return Response("Orders not found", status=status.HTTP_404_NOT_FOUND) return self.__create_transaction_and_generate_url(serializer.validated_data["payment_method"]) And my log logic: def _log_request_response(view_method, logger): @functools.wraps(view_method) def wrapper(request, *args, **kwargs): log = logging.getLogger(logger) response = view_method(request, *args, **kwargs) if isinstance(response, Response): data = response.data elif isinstance(response, JsonResponse): data = response.content.decode() else: data = f"Unprocessable type: {type(response)}" log.info(f"URL: {request.path}. Data: {request.data}. Response: {data}") return response return wrapper def log_request(name="django.request"): return functools.partial(_log_request_response, logger=name) Everything works fine, it is already been months since this code works in production, and I can see both request data and response data. However, now, I would like to get a list of local variables (and their values), of logged function (view_method). More like Sentry, when it shows a list of local variables when an exception happens (but in this case, there is no exception). TRY 1: I tried inspect.stack(), but as the function is called and finished, it ceases to exist in the call stack. Thus, inspect.stack() returns only previous functions, till wrapper. … -
With Apache's ProxyPassMatch, how do I pass on only part of my URL?
I'm running Apache 2.4 with a Python 3 / Django 3 app, both in Docker containers. If my Apache container gets a request with "/api", I would like to redirect that request to the Python container. So if my Apache request is http://localhost:9090/api/states/US I would like to redirect to the Python container using the URL http://web:8000/states/US In my virtual host file I have <VirtualHost *:80> ServerName directory.example.com ProxyPassMatch ^/api http://web:8000/(.*) ProxyPassReverse ^/api http://web:8000/(.*) But when I make the request for "http://localhost:9090/api/states/US", I get this in my Docker logs maps-web-1 | Not Found: /(.*)/api/states/US maps-apache-1 | 172.23.0.1 - - [30/Jun/2022:20:23:49 +0000] "GET /api/states/US HTTP/1.1" 404 6128 So evidently my ProxyPassMatch is not correct. How do I set that up properly? -
In a Django Forms drop-down list, how do I show text accessed via a foreign key?
I have code to edit a table "instruments", which has a foreign key to another table 'instrumenttype'. I'd like to show a drop-down list showing the text values from the instreumenttype table. My problem is that the drop-down list shows "InstrumentType object(n)" instead of the instrument type description from the other table. The update works fine; when I get the selected value and update the instruments table, the correct key id is put in. Here is the form: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from instruments.models import Instrument from instrumenttypes.models import InstrumentType # Form used to edit the data pertaining to a specific instrument class EditInstrumentForm(forms.ModelForm): instrumenttype = forms.ModelChoiceField(queryset=InstrumentType.objects.all()) class Meta: model = Instrument fields = ('instrument', 'dateAdded', 'dateRemoved', 'nickname', 'serialNo', 'status', 'instrumenttype') Here is the view snippet: def update_instrument_view(request, id=id): instrument = get_object_or_404(Instrument, id=id) if request.method == 'POST': form = EditInstrumentForm(request.POST, request.FILES, instance=instrument) if form.is_valid(): instrument.instrument = form.cleaned_data.get('instrument') instrument.dateAdded = form.cleaned_data.get('dateAdded') instrument.dateRemoved = form.cleaned_data.get('dateRemoved') instrument.nickname = form.cleaned_data.get('nickname') instrument.serialNo = form.cleaned_data.get('serialNo') instrument.status = form.cleaned_data.get('status') instrument.instrumenttype = form.cleaned_data.get('instrumenttype') instrument.save() messages.success(request, 'Your instrument has been updated.') return redirect('instrument_details', instrument.id) else: form = EditInstrumentForm(instance=instrument) messages.error(request, 'Issue updating data.') return render(request, 'instrument_update.html', {'form': form, 'instrument':instrument}) else: form = … -
Is it possible to change the title of a Django group?
In the django admin when one adds groups to a user, if one hover over the group ("Freelander" in the image below), it has a toole tip (html title) that just says "Freelancer". Is it possible to add some custom text explaining what the group is for (i.e. change the title of the option element)? Here the HTML of an the option: <option value="1" title="Freelancer">Freelancer</option> The best I can come up with is to extends the django admin template and add some JavaScript to change it by looking for the string and replacing them, but this is very "hacky" -
Django static CSS file not linking to html document
I am trying to link a css file to my html inside a django project but it does not seem to be linking. base.html <head> <title>Document</title> {% load static %} <link rel="stylesheet" href="{% static 'myApp/styles.css' %}"> </head> my folder structure [1]: https://i.stack.imgur.com/3nuwE.png -
Execute gcloud commands from python API
How can I send gcloud commands through python, I have been researching about the connection that can be made through python but I have not been able to find clear information about the process. For example what to send the command: gcloud info What it would do is to receive the information and display it in an interface but I have not been able to make the connection with the project created in google. At the moment the way to make the connection to the google shell is through subprocesses in python, here is an example: import subprocess def hello_world(request): if request.method=='GET': data = subprocess.call('gcloud info',shell=True) print(data) return true *In the case of the command presented, it is only to show that I am looking for a response from different commands, since the list of commands that will be executed are for the configuration of vlan attachments. The main idea is to be able to send the execution of commands to the google shell through an API created with python (Django) and access it from a user interface but I have not been able to connect to the specific project to be able to execute those commands. How can I … -
Unable to upload a file using Reactjs, apollo, django
Hello Im' trying to upload a file using django for the back and reactjs for the front and graphql with apollo for reactjs, graphene for django. Here is part of my code : Let's begin with the front files : index.js : import React from 'react'; import ReactDOM from 'react-dom'; import { ApolloClient, InMemoryCache } from '@apollo/client'; import { ApolloProvider } from '@apollo/client/react'; import { createUploadLink } from 'apollo-upload-client'; import App from './App'; const cache = new InMemoryCache(); const uri = 'http://localhost:8000/graphql/'; const link = createUploadLink({ uri }); const client = new ApolloClient({ cache, link }); ReactDOM.render( <React.StrictMode> <ApolloProvider client={client}> <App /> </ApolloProvider> </React.StrictMode>, document.getElementById('root') ); App.js import React from 'react'; import { gql, useMutation } from '@apollo/client'; const MUTATION = gql` mutation ($file: Upload!) { imageUpload(file: $file) { success } } `; function App() { const [mutate] = useMutation(MUTATION); function onChange({ target: { validity, value } }){ if (validity.valid) { const file = new Blob([value], { type: "text/plain" }); file.name = "text.txt"; mutate({ variables: { file: file } }); } } return <input type="file" onChange={onChange} />; } export default App; And now for the back : import graphene from .models import Todo from graphene_django import DjangoObjectType, DjangoListField from graphql_jwt.decorators … -
Avrage rating calculation not working after migration django
My code was doing what it should before the migration of calculating the avrage rating. After a migration it just dident calculate the avrage rating. It seems like the migration dident notice the code i had in choices= RATINGS) . Anyone got any idea how i can fix it and get the code to notice the choices again? Since it worked fine when testing it just before migrations. **code from model.py** class Review(models.Model): product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE) rating = models.IntegerField(default=3) content = models.TextField() created_by = models.ForeignKey(User, related_name='reviews', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) RATINGS = (('1 ',1),('2 ',2), ('3 ',3),('4 ',4),('5 ',5)) rating = models.CharField(max_length=7,choices= RATINGS) def __str__(self): return '%s - %s' % (self.product.name, self.created_by) code in the migration file: class Migration(migrations.Migration): dependencies = [ ('products', '0004_review'), ] operations = [ migrations.AlterField( model_name='review', name='rating', field=models.CharField(choices=[('1 ', 1), ('2 ', 2), ('3 ', 3), ('4 ', 4), ('5 ', 5)], max_length=7), ), ] And this a snippet of the migration after i notice the avrage rating was gone even tho the code was same after migration in models.py: