Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How is a Django app on Google App Engine structured?
I have read through all of Google's documentation on App Engine and various other blog posts but I still do not have a clear idea on the structure of a Django app running on App engine. As I see things, App engine instances are attached to one SQL database and Google provides auto-scaling and auto load balancing that will replicate your SQL database according to current load. What does this mean in terms of Django python code? All it seems to take to deploy a Django app is to run glcoud app deploy. If an App Engine instance's SQL database is scaled and replicated automatically in real time, is the Django app replicated along side them? Or will all HTTPS requests go through a single Django app no matter the replications? In addition, is the Django backend code physically hugging the database it is connected to? -
why do I receive an error when I want to start my django app?
When I start my dajngo app with the "manage.py runserver" command, I receive the mistake : `Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?` However, I've just verify the installation of all requirements, and my virtual environment is well activated. So I don't know why it's not working. Thank for all of your answers ! -
Django prefetch_related for M2M with through relationship
I'm try to decreasing queries to single query but queryset returns 2 queries. I tried some method but nothing changed Models.py class Match(models.Model): ... participant = models.ManyToManyField(TournamentTeam, through='MatchParticipant') ... class MatchParticipant(models.Model): match = models.ForeignKey(Match, on_delete=models.SET_NULL, null=True, blank=True) team = models.ForeignKey(TournamentTeam, on_delete=models.SET_NULL, null=True, blank=True) views.py queryset = Match.objects.prefetch_related( Prefetch( 'participant', queryset=MatchParticipant.objects.select_related( 'match','team' ), ), ).select_related('some_foreignkey',).get(slug=slug) -
Why are my Django importations no longer working properly
I've been using Django with pycharm and it's been working fine, but suddenly I couldn't use Django without opening a virtual environment and installing it, then I noticed I could no longer import path, include, views, generic etc even on my old project where they used to work, they're no longer responsive. I've spent a lot of time trying to resolve this but to no avail. This happens both in pycharm and vscode. thanks -
Object of type JpegImageFile is not JSON serializable
I'm trying to use celery in my web app, but I don't know exactly how. I take out the image update in task, and he complains about the serializer constantly tasks.py from celery import shared_task @shared_task def update_image(image, width, heigth): output_size = (width, heigth) image.thumbnail(output_size) image.save() models.py: def save(self): img = Image.open(self.image.path) task = update_image.delay(img, self.width, self.heigth) views.py: def put(self, request, pk): saved_content = get_object_or_404(Content.objects.all(), pk=pk) data = request.data.get('content') serializer = ContentSerializer( instance=saved_content, data=data, partial=True) if serializer.is_valid(raise_exception=True): content_saved = serializer.save() return Response({ "success": "Picture '{}' updated successfully".format(content_saved.id) }) Error: Object of type JpegImageFile is not JSON serializable Request Method: PUT -
Django changing model booleanfield not working
model public = models.BooleanField(default=False) view @login_required def topic_visibility(request, topic_id, visibility): """Change topic visibility, then redirect to topics page""" topic = Topic.objects.get(id=topic_id) check_instance_ownership(request, topic) if visibility == 0: topic.public = False elif visibility == 1: topic.public = True return redirect('learning_logs:topic', topic_id = topic_id) url pattern path('topic_visibility/<int:topic_id>/<int:visibility>', views.topic_visibility, name="topic_visibility"), A button dropdown allows the user to select whether they with for the model to be public (True) or private (False). When the user visits the respective url that interacts with the view, nothing is changed. I suspect it may have something to do with the topic model not being saved? -
what does " python manage.py migrate " in django do exactly?
I am new to django, and the tutorial directly applied this command without explaining. After searching, I found out something call migrations in django, but didnt understand it either as I am a complete newbie in this What does the python manage.py migrate command do exactly? What are migrations? -
Use format in query parameter for ViewSet in Django Rest Framework
I have a ViewSet which returns JSON object. Now I need to return CSV file for download, using the existing ViewSet. If I will add "format" as a query parameter, like "site.com/api/answers?format=csv" django will return me "Not Found", before reaching the ViewSet: { "error": { "message": "Not found." }, "result": false } My ViewSet: class AnswerViewSet(ViewSet): def list(self, request: Request) -> Response: request_serializer = AnswerRequestSerializer(data=request.query_params) response_serializer.is_valid() return Response(response_serializer.data) Where should I change this behavior to return CSV file, if I add format=csv to a query? -
Django website is displaying "It works! Python 3.6.8"
I recently deployed a Django website on namecheap and it has been running properly not until yesterday when I started seeing: It works! Python 3.6.8 Please what can I do rectify this issue. -
Django model fields don't show up in Admin page
I am a beginner to Django and am having trouble seeing all the Model Fields when I try to load them on the Django Admin page. I add the app correctly in the settings page, do a relative import to the admin page and successfully get the model to show up in the Admin page, but the problem is that most of the time, Fields that I have entered are missing. I usually just displays the last one or two and only if they are TextFields. This is all the Fields I enter into the text editor But this is all I end up seeing -
Django Model save() retains mutable reference for JSONFields()
# Model contains only one JSON field class TestModel(models.Model): field = JSONField(default=dict) # Dictionary, assigned to model.field field_json = {"test": 5} model = TestModel(field = field_json) model.save() # Returns true. WHY??? print(id(model.field) == id(field_json)) After saving a model, shouldn't the model refresh from db? Why is the model field retaining a mutable reference to the original dictionary object? -
Pass a file to xlrd.open_workbook()
I am trying to open a file with xlrd.open_workbook() but am getting an error: expected str, bytes or os.PathLike object, not InMemoryUploadedFile Here's my code: def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_file(request.FILES['file']) def handle_file(f): book = xlrd.open_workbook(f) What's the correct way to pass a file? -
Exception happened during processing of request from ('127.0.0.1', 59369)
I am getting this error in the command line, but it isn't affecting the website in anyway now, but I want to know what can be the cause of this error. Does anyone know? Exception happened during processing of request from ('127.0.0.1', 59369) Traceback (most recent call last): File "C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle self.handle_one_request() File "C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
Parsing error: Expected corresponding JSX closing tag for <Route>?
Am trying to link my car page so when clicked on it could go to that page but this error keeps on popping up saying jsx closing tag for route and don't know why it could be popping up as my tags are closed? import React from 'react'; import logo from './logo.svg'; import './App.css'; import Header from './components/header'; import Footer from './components/footer'; import Home from './components/home'; import About from './components/about'; import Car from './components/car'; import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'; function App() { return ( <Router> <Switch> <Route exact path="/"> {create_page(<Home />)} </Route> <Route path="/home"> {create_page(<Home />)} </Route> <Route path="/about"> {create_page(<About />)} <Route path="/home"> {create_page(<Home />)} </Route> <Route path="/car"> {create_page(<Car />)} </Route> </Switch> **Here is where I keep on trying to fix the code but it keeps on saying close tag for route yet route is already closed?** ); } function create_page(page) { return ( <div className="App"> <div className="header"> <Header /> </div> <div class = "page"> {page} </div> <footer> <Footer /> </footer> </div>) } export default App; This is the error that pops up Parsing error: Expected corresponding JSX closing tag for </Route> </Switch> ^ -
Django - edit uploaded file Before final saving
i want to make a site for uploading and processing of images. sometimes, some files need some editing before saving. i want edit the uploaded file before saving it to media dir (mostly to avoid IO interaction and only keep original file in memory and discard after saving edit version). edit: so i thought i have to run the edit function in POST, and change information in request.FILES. but i failed, and don't know what to do anymore. NOTE: im mostly looking for a way to do it via class views. here's some code for refrence: The model: class FilePatient(models.Model): file_imag = models.FileField(upload_to='') The View: class FileAddView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, CreateView): model = FilePatient fields = ['file_imag'] def post(self, request, *args, **kwargs): if request.FILES['file_imag'].name.endswith('.png'): newFile=editFile(request.FILES['image_imag']) # what to do, what not to do return super().post(request, *args, **kwargs) -
Django in Heroku throws error column does not exist
I'm trying to deploy my django project to heroku, however it's not working particularly well. When I try to make an account, everything works fine, and logging in is fine. Locally, everything works as intended. However, when I try to create a new model instance on heroku, it throws the following error: ProgrammingError at /contracts/new/ column "completed" of relation "contracts_clientcontract" does not exist LINE 1: INSERT INTO "contracts_clientcontract" ("UUID", "completed",... ^ I tried the advice given at Django Programming error column does not exist even after running migrations but it didn't work. So I tried removing migration history, and that didn't work. So I made a version of the project that had no migrations at all and sent that to heroku, and then ran both makemigrations and migrate using heroku run bash, and I still get the same error. I'm not sure what's going on here... Is it possible that because heroku uses postgres that I need to change the projects settings to reflect that, since it's using sqlite3? If so, I'll feel dumb but validated. Can anyone point me in the right direction? -
Can't install Django 2.1.6
I used pip install Django==2.1.6 There is error ERROR: No matching distribution found for Django==2.1.6 How to install Django 2.1.6? Don't want to install it from git because need to validate hashes. -
django with jquery select values
Hello I need some help with intergrating django to jquery am not sure of how to go about it but I have given it an attempt.. I need when someone clicks the award placeholder depending on the value they have chosen the nominee placeholder displays the nominees nominated under that award from the database table called Nominee Here is the form code: <form class="form-group" method="post" id="formsubmit"> {% csrf_token %} <div class="row"> <div class="col-md-6"> <label>FOR AWARD</label> <select name="award" class="form-control" id="award" required> {% for name in award%} <option>{{ name.award_name }}</option> {% endfor %} </select> </div> <div class="col-md-12"> <label>NOMINEE NAME</label> <select class="form-control" name="nominee" id="nominee" required> <option value=""></option> </select> </div> </form> here is the jquery code <script> $("#award").change(function () {// get the url of the `load_cities` view var award = $("#award"); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: {% url 'submit' %}; // set the url of the request (= localhost:8000/hr/ajax/load-cities/) data: { 'award': award// add the country id to the GET parameters }, success: function (data) { // `data` is the return of the `load_cities` view function $("#nominee").html(data); // replace the contents of the city input with the data that came from the … -
Invalid salt when logging in via django admin panel
I'm having some trouble hosting a django API on a separate server. When using localhost everything works, however when I log in to the server admin panel I get an "invalid salt" error. Originally, I had my own login method that used bcrypt, but I decided to scrap that in favor of using facebook authentication. I've removed all references to bcrypt from my views. The problem lies with the built in admin interface. I haven't modified the code for that at all, but I am unable to log in. I can share my code, but I'm not even sure what files would be relevant to share, so I'm happy to update as needed. -
Django how make a filter of foreignkey based on parent foreignkey selected in other form?
I'm trying to create a form for edit table Person, but in this form field Car must be filtered by selected Company. I'm very new to python/django so this may be a bad approach, high level suggestions welcome. Here is what I have: I have 3 models in models.py: from django.db import models class Company(models.Model): company = models.CharField(max_length=25) def __str__(self): return self.company class Car(models.Model): car = models.CharField(max_length=25) company = models.ForeignKey(Company, on_delete = models.CASCADE) def __str__(self): return self.car class Person(models.Model): name = models.CharField(max_length=20) car = models.ForeignKey(Car, on_delete = models.CASCADE) def __str__(self): return self.name views.py: def index(request): people = Person.objects.all().select_related('car__company') table = PersonTable(people) return render(request, 'index.html', {'table': table}) def edit(request, id): person = Person.objects.get(id = id) car = Car.objects.get(id = person.car_id) company = Company.objects.get(id = car.company_id) if request.method == 'POST': form = PersonForm(car.company_id, request.POST, instance=person) if form.is_valid(): form.save() return redirect('/person/') else: companys = CompanyForm(instance=company) form = PersonForm(car.company_id, instance=person) return render(request, 'person/edit.html', {'companys':companys, 'form':form}) def Company_select(request): if request.method == 'POST': form = CompanySelectForm(request.POST) if form.is_valid: return redirect('/person/edit/1/') # Return to form PersonForm with id=1. # How to return selected Company? # How to return to page with other id? else: form = CompanySelectForm() return render(request, 'person/company_select.html', {'form':form}) urls.py: app_name = 'person' urlpatterns = … -
Django Rest Framework Nested Serializer of Many to Many Self field
I have a recipe model and recipeIngredient model. I can retriev through a nested serializer recipes and their ingredients. However, I want to link recipes with recipes and therefore I want to retrieve the Ingredients of the subrecipes too. But I don't know how to achieve this. These are the following models/serializer in my project: models.py class Recipe(models.Model): name = models.CharField(max_length=150, unique=True) subrecipe = models.ManyToManyField('self', blank=True, symmetrical=False) class Ingredient(models.Model): name = models.CharField(max_length=150) class RecipeIngredient(models.Model): amount = models.IntegerField() unit = models.ForeignKey(Measurement, on_delete=models.PROTECT) ingredient = models.ForeignKey(Ingredient, on_delete=models.PROTECT) recipe = models.ForeignKey(Recipe, on_delete=models.PROTECT, related_name='ingredients') serializers.py class RecipeIngredientSerializer(serializers.ModelSerializer): ingredient_name = serializers.ReadOnlyField(source='ingredient.name') recipe_name = serializers.ReadOnlyField(source='recipe.name') unit_name = serializers.ReadOnlyField(source='measurement.name') class Meta: model = models.RecipeIngredient fields = '__all__' class RecipeSerializer(serializers.ModelSerializer): ingredients = RecipeIngredientSerializer(many=True, read_only=True) class Meta: model = models.Recipe fields = '__all__' With the nested RecipeIngredientSerializer all of the ingredients that are linked to the recipe are shown. "id": 1, "ingredients": [ { "id": 2, "ingredient_name": "Water", "recipe_name": "Bread", "amount": 100, "unit": 1, "ingredient": 1, "recipe": 1 } ], "name": "Bread", "subrecipe": [ 3, 2 ] However, I would like to link recipes with other recipes. The problem is I don't know how to retriev the ingredients for the subrecipes. As in the nested example above, I want … -
Django staticfiles JS, JSON and CSS Error 404
I want to add my Gatsby JS' public folder that I created with npm run build to be served to Django as_view. Django keeps throwing 404 Error at me when I'm trying to load the staticfiles and the index.html from STATICFILES_DIRS. I don't understand how Django is not able to find the JSON file e.g /app-data.json even if I provide an absolute path. Note: I tried python3 manage.py runserver --insecure (and without insecure as well) - didn't work. Directory structure: ./frontend - ./public - ./codeblock - ./codeblock/1-index - ./staticfiles - ./staticfiles/d - ./page-data - /app-data.json - ./index.html - ... ./backend - ./backend - settings.py settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False INSTALLED_APPS = [ ... 'django.contrib.staticfiles', BACKEND_DIR = BASE_DIR FRONTEND_DIR = os.path.abspath( os.path.join(BACKEND_DIR, '..', 'frontend')) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(FRONTEND_DIR, 'public'), os.path.join(FRONTEND_DIR, 'public', 'page-data'), ] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) urls.py ...imports urlpatterns = [ url('test/', views.FrontendAppView.as_view()), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) index.html In the HTML file if I define the path with /static/, such as href="/static/webpack-runtime-4145e7520a88c179d990.js", then Django can pull in the JS static files, otherwise 404 Error. <!DOCTYPE html> <html lang="en"> <head> <link as="script" rel="preload" href="webpack-runtime-4145e7520a88c179d990.js" /> <link as="script" rel="preload" href="commons-926e13980b7ff3c9526c.js" /> <link as="script" rel="preload" href="app-425daa4026ff9a50d14f.js" /> … -
Get output of django runserver background process
I have Django runserver process with pid 8496 in background. How can I view its logs or redirect the logs to a file without restarting the process? On one of the links, I found that I can do that using /proc/8496 directory. I tried accessing /proc directory but it returns a no such file or directory error. -
Convert doc to pdf faster than saving to .docx then using convert to pdf using doc2pdf library or pywin32?
Pywin32 save .docx as pdf This SO post does explain how to save a file as a pdf on windows. My goal is to accept information from the user through a form through the webpage and send him back a pdf out of that information. I have been given a template word docx file to pick tables and put in some data, save as pdf and send back file attachment response. Currently the code works but I get the pdf around 1 minute after. You can see that there aren't many additions that I m making. Running it on the server might give more poorer performance. Currently I ran it on localhost. It would be good if I dont need to save the document as word file first and just convert the doc object in the code backend.py to .pdf(as an object) and send it back to the view to send it as a FileResponse. I 'm using a win 10 64 bit to create the code. (A solution which is compatible with linux too is the requirement.So please prefer the same if possible.) Current Code views.py def index(request): if request.method == "POST": form = InputData(request.POST) if form.is_valid(): check, data … -
AJAX unable to define the key's method in Django
First off, sorry for the odd phrasing of the title. I currently have a webapp that allows users to order food from a resturant. In the menu html I currently have the following snippet. {% if latest_order %} <table class="table" id="checkout-table"> <thead class="thead-dark"> <tr> <th scope="col"></th> <th scope="col">YOUR</th> <th scope="col">CART</th> <th scope="col"></th> </tr> </thead> {% for order in latest_order %} <tr> <td>{{ order.order_name }}</td> <td class="change-quantity"> <form method="post"> {% csrf_token %} <div class="row"> <div class="col-sm"> <button type="submit" name="remove_quantity" value="{{ order.id }}" class="mr-3 btn btn-outline-info">-</button> </div> <div class="col-sm"> {{ order.order_quantity }} </div> <div class="col-sm"> <button type="submit" name="add_quantity" value="{{ order.id }}" class="ml-3 btn btn-outline-info">+</button> </div> </div> </form> </td> <td>${{ order.order_individual_price }}</td> in my JS I have the following AJAX code running $(document).ready(function(){ $(".ramen").click(function(event){ event.preventDefault() var serializedData = $("#ramen-form").serialize() $.ajax({ url: $("ramen-form").data("url"), data: serializedData, type: 'post', success: function(response) { $("#checkout-table").append('<tr><td>' + response.new_order.order_name + '</td><td class="change-quantity">' + '<form method="post">{% csrf_token %}<div class="row"><div class="col-sm">' + '<button type="submit" name="remove_quantity" value="{{ order.id }}"class="mr-3 btn btn-outline-info">-</button>' + '</div><div class="col-sm">'+ response.new_order.order_quantity +'</div><div class="col-sm">' + '<button type="submit" name="add_quantity" value="{{ order.id }}" class="ml-3 btn btn-outline-info">+</button>' + '</div></div></form></td><td>$'+ response.new_order.order_individual_price +'</td><form method="post">{% csrf_token %}<th>' + '<button type="submit" name="delete" value="{{ order.id }}" class="btn btn-danger">Delete Item</button></th></form></tr>') } }) }); }) In my views.py I have …