Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Files (except pdfs) Corrupted when uploading django restframework api
Hey so i'm having a bit of an issue. I wrote a django restframework api for uploading files to my local directory. It seems like it works perfectly fine when it comes to pdfs, but any other type of format damages the file and make it unable to open. (this includes png/jpg/any other picture format, txt files, xlsx files, and etc) The files are saved perfectly fine in the correct path, they're named appropriately without issue. class UploadInvoiceFile(APIView): parser_classes = (FileUploadParser, MultiPartParser) def put(self, request, filename, specific_path='admin'): file_obj = request.data['file'] file_path = settings.INVOICE_URL[admin] file = file_path+'/'+filename if not os.path.exists(file_path): os.makedirs(file_path) with open(file, 'wb+') as destination: for chunk in file_obj.chunks(): destination.write(chunk) return Response(status=204) -
Is there a way to roll back all django app migrations?
I'm bootstrapping a new django project, and my team usually makes a 'setup/reset' script that rebuilds containers as well as drops(unless it doesnt exist yet) and rebuilds the database from scratch. I found the manage.py flush command for dropping the data, but I also want to revert all migrations. I could only find a command for rolling back the migrations of a single app at a time: manage.py migrate <app_name> zero Is there a way I can do that for every app, or would I have to list them out in the script? We do have the manage.py migrate command that migrates everything, so I basically just want the opposite of that. If it's not easily possible, I'll probably just make the db container drop and rebuild the database Thanks! -
Django REST Framework - Generic Class-based views - DELETE request doesn't work
I have an issue with deleting an instance of a model (let's call it A) which has an instance of another model (B) related to A by Foreign Key constraint, and fails to delete. It's using CASCADE parameter, however I get response 500 which in the tracebacks just says that the server has crashed/database went into recovery mode. The following is my code: views.py class TaskInstance(generics.RetrieveUpdateDestroyAPIView): """ Returns Task instance """ queryset = Task.objects.all() serializer_class = TaskSerializer class StepList(generics.ListCreateAPIView): """ List all Steps (OR for specified task), or create a new one """ queryset = Step.objects.all() serializer_class = StepSerializer filter_fields = ('task',) models.py class Task(models.Model): name = models.CharField(max_length=25, blank=False) cat = models.ForeignKey(Category, on_delete=models.CASCADE) class Meta: ordering = ('id',) class Step(models.Model): name = models.CharField(max_length=25, blank=False) completed = models.BooleanField(blank=True, default=False) task = models.ForeignKey(Task, on_delete=models.CASCADE) class Meta: ordering = ('id',) serializers.py class TaskSerializer(serializers.ModelSerializer): cat = serializers.PrimaryKeyRelatedField(queryset=Category.objects.all()) class Meta: model = Task fields = ('id', 'name', 'cat') class StepSerializer(serializers.ModelSerializer): task = serializers.PrimaryKeyRelatedField(queryset=Task.objects.all()) class Meta: model = Step fields = ('id', 'name', 'completed', 'task') My perfect scenario: I'd like to be able to send a DELETE request for specific Task model, which deletes every Step model that relates to it. I'd appreciate any help! -
How to extract INT from Queryset
I am trying to create a graph that dynamically updates based on date and count of POs. Model: class JobOrder(models.Model): status = models.CharField('status', choices=STATUS, max_length=200, default="Waiting") job_order = models.IntegerField(primary_key=True) remarks = models.CharField(max_length=45, blank=True, null=True) rush_order = models.IntegerField() date_issued = models.DateField('date_issued', auto_now_add=True) date_required = models.DateField() client = models.ForeignKey(Client, on_delete= models.CASCADE) total_amount = models.FloatField() Query from View: POs = JobOrder.objects.values('date_issued__year', 'date_issued__month').annotate(c=Count('id')).values('c') Passing it in a javascript code in HTML: function salesComparisonChart() { var POComparisson = google.visualization.arrayToDataTable([ ['Month', 'Count'], {% for POs in POs %} ['Month', parseInt('{{POs}}')], {% endfor %} ]); With my current code, the data that is being passed looks like this: {'c': 4} {'c': 2} {'c': 1} -
Why is my Django loop displaying the same image in svg viewbox?
I am using the django framework and trying to display images from the model in a polygon. For this I am using svg. Currently it just displays the smae image multiple times instead of displaying all images in the database. Here is my code: {% if images %} <section id="gallery"> <ul id="hexGrid"> {% for image in images %} <li class="hex"> <svg viewbox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg"> <defs> <pattern id="img" patternUnits="userSpaceOnUse" width="100" height="100"> <image xlink:href="{{image.src.url}}" x="-25" width="150" height="100" /> </pattern> </defs> <polygon id="hex" points="50 1 95 25 95 75 50 99 5 75 5 25" fill="url(#img)"/> </svg> </li> {% endfor %} </ul> </section> {% else %} <p> No Posts </p> {% endif %} Here is my model: from django.db import models class Images(models.Model): title = models.CharField(max_length=200) src = models.FileField(upload_to='images/', null=True, verbose_name="") What am I doing wrong? -
Errno 13 while running docker-compose up
I'm building an application using django and I wanted to add docker to this project. I'm trying to run sudo docker-compose up Which gives me this output: ERROR: .IOError: [Errno 13] Permission denied: './docker-compose.yml' I checked the permissions using GUI. Everything is fine. I'm trying to run my app from an mounted drive. I also tested it on other drives. The only drive this problem does not appear is my main drive running Ubuntu 18.04. Looking forward to some answers -
Django access nested object field in serializer
I Django-Rest have a class A that contain the field a_field, and a class B that contain the fields b_field and a_class_ref. How it is possible in the serializer of B to do something like : class a_serializer(): class Meta: model= B fields= [ 'b_field', 'a_field` ] Thank you -
Why does Django migration using MSsql suggest success, but fails to create tables?
I'm new to Django, and fighting with it by using a non-supported MS_SQL for my DBMS. It's where I have my work experience, but I've been teaching AP Java since the Dot.Bomb ending 2003. Trying to regain some relevance by learning Bootstrap and Django, preparing to one day return to a production environment. (Basically saying I'm not an idiot, but I feel like one as I fight with getting Django to play well with MS_SQL.) My graphics below show that I've taken the expected steps, seen "migration" complete successfully, and yet the tables I expected to be created never materialized. I'm thus far assuming that my migration transaction was rolled back, but if so, I was never informed of such, and instead was mean-spiritedly greeted with pretty "OK" comments. Grrr! Any suggestions on where in this pipeline I goofed? Thank you! W enter image description here enter image description here -
how to use django annotate with foreign key
Consider simple Django models class Journey(models.Model): vrn=models.CharField(max_length=200) # Vehicle Reg No kilo=models.FloatField() class J_user(models.Model): jdi=models.ForeignKey(Journey, related_name="Journey_User",on_delete = models.DO_NOTHING,) uid=models.IntegerField() It's easy to annotate in a single table like if we want sum total driven kilometers for each vehicle (vrn represent registration number of the vehicle) Journey.objects.values('vrn').annotate(Total_kilo=Sum('kilo')) Now i want to make a query that will return how many kilometers each user has traveled in each car. Let Data of Journey table Data of J_user table Then the result should be Thanks for your help. -
Djoser: trigger action on user account activation
I have djoser integrated on my django project, and I need to create a stripe customer_id on account activation, how can I do this? I've been searching on djoser doc, but there is nothing about customizing activation, or passing a callback method. -
Django, path/urls
please explain me why following code works with http://127.0.0.1:8000/index/1/ and doesn't for http://127.0.0.1:8000/1/: mysite\urls.py urlpatterns = [ path('index/', include('polls.urls')), path('1/', include ('polls.urls')), ] polls\urls.py urlpatterns = [ path('1/', views.polls, name='z'), path('', views.index, name='index'), ] Does Django not accept absent of some indexlike path, is everything built on it? -
How To Check If A Model Has A Reference To It
Say I have an address (think street address) model in django and that is referenced by jobs (think job sites) and customers (think mailing addresses). When executing a query, is it possible to filter only rows which do not have a reference to them? Models class Address(models.Model): street = models.TextField() suite = models.TextField() city = models.TextField() state = models.TextField() county = models.TextField(default="") country = models.TextField(default= "USA") zip = models.TextField() notes = models.TextField() class Customer(models.Model ): firstname = models.TextField(null=False) lastname = models.TextField(blank=True) address = models.ForeignKey(Address,null=True,blank=True,default=None) class Job(models.Model): number=models.IntegerField(null=False) name=models.CharField(max_length=100,default="") address = models.ForeignKey(Address,null=True) Desired Functionality #get all addresses that don't have a job or customer referencing it addresses = Address.objects.filter(job_set_count = 0, customer_set_count=0) PS Would this be the scenario to use the "OneToOne" relationship? -
I am new to django python i want to know if there is any platform like firebase for django
Previously i build some websites using angularjs with firebase integratiion. Which was a good experience but for now i am moving to django python but i haven't found anything like firebase for django. -
Django: select_related with multi table inheritance
I have the following model structure: class A(models.Model): prop_a = models.CharField(max_length=255) class B(A): prop_b = models.CharField(max_length=255) class C(A): prop_c = models.CharField(max_length=255) class D(models.Model): fk = models.ForeignKey('A') So essentially, I have a model (D) which has a foreign key to an 'abstract' model (A) which is subclassed by B and C. Now, when I run D.objects.all().select_related(), only the properties of Aare queried. I assume this is because at query time, Django does not know which child class the fk is an instance of (and neither do I in my current structure). Is there any way to query the properties of the child class without changing the model structure? I also tried prefetch_related and tried using an InheritanceManager from django-model-utils, both to no avail. -
Array/Jsonb update field: psycopg2.ProgrammingError: column "waypoints" is of type jsonb[] but expression is of type text[]
Using Django 2.1/ python 3.6 I'm looking to update a field on an existing model. The field isof the following type: from django.contrib.postgres.fields import ( ArrayField, JSONField ) waypoints = ArrayField( JSONField( default=list, null=True, blank=True ), size=None, null=True, blank=True ) And the field will store data in the format: [ {'lat': 63.123334, 'lon': 13.433918, 'date': '2018-08-23 11:00:00', 'direction': 123, 'rpm': 0}, {'lat': 42.315119, 'lon': -3.213883, 'date': '2018-08-12 09:15:00', 'direction': 95.45, 'rpm': 3998}, {'lat': 51.763023, 'lon': 7.376109, 'date': '2018-08-19 03:30:00', 'direction': 45.76, 'rpm': 7823} ] I am acutely aware of the fact that this is not good practice, and that the better method would be to use a foreign key with another model, but my hands are tied. My code is: scheduler_response = { "result": { "time": 23, "total_consumption": 98117, "waypoints": [ { "lat": 42.315119, "lon": -3.213883, "date": "2018-08-12 09:15:00", "direction": 95.45, "rpm": 3998, "cumulative_consumption": 0 }, { "lat": 51.763023, "lon": 7.376109, "date": "2018-08-19 03:30:00", "direction": 45.76, "rpm": 7823, "cumulative_consumption": 44298 }, { "lat": 63.123334, "lon": 13.433918, "date": "2018-08-23 11:00:00", "direction": 123, "rpm": 0, "cumulative_consumption": 98117 } ] } } scheduler_waypoints = scheduler_response.get('result').get('waypoints') job_updates = {} job_updates['waypoints'] = scheduler_waypoints job_updates['total_consumption'] = scheduler_response.get('total_consumption') serialized_job = JobSerializer(active_job, data=job_updates, partial=True) if serialized_job.is_valid(): print('is_valid') print(serialized_job.validated_data) … -
localhost cannot server static files docker-compose
So I'm having this really weird problem. I'm working in django and in the base directory and I ran docker-compose build and docker compose up-d. I'm running on mac so in the docker-compose.yml, so the var/www/static directory doesn't exist. I changed the volume line for static files to "basedirectory/static:/opt/app/static" (maybe that's my problem??? I don't know though because I tried a ton of different directories and nothing took). After the build completes "successfully", when I go to localhost:8000 I get the following error 1. But I can still navigate to localhost:8000/admin. The problem here is that none of my styling loads because all the css files are in the static directory. So then I get these errors 2. I think the problem is that the files are not actually going in the base/localhost directory. But honestly I'm just really lost. Any and all help would be greatly appreciated!! Thanks so much :)) -
Django ManyToManyField and Form
I'm writing my first Django App and I have two classes in my models.py file, Ingredient and Meal. A food has many ingredients and you're suppose to be able to set the quantity of each ingredient in the meal, so that's my models.py: class Ingredient(models.Model): name = models.CharField(max_length=200) class Meal(models.Model): name = models.CharField(max_length=200) ingredients = models.ManyToManyField(Ingredient, through='Recipe_Ingredient') class Recipe_Ingredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) quantity = models.FloatField() UNITY_CHOICES = ( ('g', 'Gram(s)'), ('kg', 'Kilogram(s)'), ('l', 'Liter(s)'), ('cl', 'Centiliter(s)'), ) quantityUnit = models.CharField( max_length=2, choices=UNITY_CHOICES, default='g', ) The Recipe_Ingrent class is the ManyToMany associate table to store the quantity. The problem here is that I don't know how to use Forms in this case. I have a template meal_edit.html that calls a django form in form.py. To add an ingredient my form would be simple, like this: from .models import Ingredient class IngridientForm(forms.ModelForm): class Meta: model = Ingredient fields = ('name',) So, how am I suppose to make a form that will create a recipe with multiple ingredients and a quantity for each of those? -
Django DRF views filter ManyToMany queryset
There are two models class User(Model) and class Loan(Model): parents = models.ManyToManyField(User, related_name='parents', verbose_name='Родители') # .objects.all().filter(user_type=User.PARENT) children = models.ManyToManyField(User, related_name='children', verbose_name='Дети') #.objects.all().filter(user_type=User.CHILD) and view based on DRF class ChildrenViewset(viewsets.ModelViewSet): queryset = User.objects.all() def get_queryset(self): queryset = User.objects.all() # TODO here i need to write filter return queryset How I can filter quryset. to select all children for defined parent. I have some parent_identity (can be called id or pk) what i expect to see queryset = User.objects.filter(children__loan_set__parent__identoty=parent_identity) return queryset -
Is there an exception that would rollback an Django atomic transaction without being propagated?
I created an exception class MyOwnRollBack(Exception): pass only to be able to rollback a transaction without it being raised beyond the transaction: try: with transaction.atomic(): # do stuff raise MyOwnRollBack except MyOwnRollBack: pass Is there an exception that transaction.atomic() won't let propagate, similar to this code I wrote? -
django rest update_or_create
Background: I am trying to create a system which allows users to vote on comments written by other users (similar to Reddit). Users have the choice of three vote values: -1, 0, or 1. I have created a POST API (using django rest-framework) that will store a user's vote with respect to a particular comment. If the user has already voted on the given comment, then it will update the existing user’s vote value to the new one. I drew inspiration from this post:Django RF update_or_create Problem: Once a comment has had one user submit a vote on it, Django creates a duplicate comment object with the same ID/primary key whenever another user votes on the same comment. I have taken a screenshot of my admin page where it says I have 3 objects to select but only a single comment. Why is it doing this and how can I prevent it? Screenshot of my comment admin page I am new to Django. I suspect I might be doing something wrong when I define my own "create" method in my serializer. I'd appreciate any help. Thanks! models.py: Comment model: class Comment(models.Model): location_property_category = models.ForeignKey('locations.LocationPropertyCategory',on_delete=models.CASCADE,related_name='comments',null=True) author = models.ForeignKey('auth.User',on_delete=models.PROTECT,related_name='comments') location = models.ForeignKey('locations.Location',on_delete=models.CASCADE,related_name='comments') … -
Django multifile upload doesn't send files to directory
I'd like to implement a multifile upload feature into a site. There is already an upload feature on the site, but for single files. I'm following loosely the Simple Is Better Than Complex: Django Multiple Files Upload Using Ajax. My code: views->mulit_upload.py class BasicUploadView(View): def get(self, request): files_list = Multi_File.objects.all() #files_list = ['testing_123'] print ("files_list: {0}".format(files_list)) return render(self.request, 'myproject/multi_upload.html', {'filesList': files_list}) def post(self, request): form = FileForm(self.request.POST, self.request.FILES) if form.is_valid(): multiFile = form.save() data = {'is_valid': True, 'name': multiFile.file.name, 'url': multiFile.file.url} else: data = {'is_valid': False} return JsonResponse(data) models.py class Multi_File(models.Model): title = models.CharField(max_length=255, blank=True) file = models.FileField(upload_to='files/') uploaded_at = models.DateTimeField(auto_now_add=True) forms.py class FileForm(forms.ModelForm): class Meta: model = Multi_File fields = ('file', ) multi_upload.html {% load static %} {% block javascript %} <script src="{% static 'myproject/js/jQuery-File-Upload-9.14.1/js/vendor/jquery.ui.widget.js' %}"></script> <script src="{% static 'myproject/js/jQuery-File-Upload-9.14.1/js/jquery.iframe-transport.js' %}"></script> <script src="{% static 'myproject/js/jQuery-File-Upload-9.14.1/js/jquery.fileupload.js' %}"></script> <script src="{% static 'myproject/upload-files.js' %}"></script> {% endblock %} {# 1. BUTTON TO TRIGGER THE ACTION #} <div class="col-md-4"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile" multiple> <button type="submit">Upload<span class="glyphicon glyphicon-cloud-upload"></span> </button> </form> </div> {# 2. FILE INPUT TO BE USED BY THE PLUG-IN #} <input id="fileupload" type="file" name="myfile" multiple style="display: none;" data-url="{% url 'myproject:multi_import' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> {# 3. … -
Linking Django QuerySets in a similar way to annotations
I have the following models: class Foo(models.Model) bar = models.ForeignKey(Bar, on_delete=models.PROTECT) class Bar(models.Model) ... class Baz(models.Model) bar = models.ForeignKey(Bar, on_delete=models.PROTECT) I want to know if it is possible to do something similar to an annotation to link a Baz queryset to a pre-filtered Foo queryset. Something like: queryset = Foo.objects.some_filter() .annotate(documents=QuerySet('bar__baz_set.another_filter()')) Note that the Baz queryset is also filtered, and that a Bar may not always have a Baz -
Django/React - You may need an appropriate loader to handle this file type
I'm having an error running the webpack dev script, this is the error. This are the codes: App.js import React from "react"; import ReactDOM from "react-dom"; import DataProvider from "./DataProvider"; import Table from "./Table"; import Form from "./Form"; const App = () => ( <React.Fragment> <DataProvider endpoint="api/lead/" render={data => <Table data={data} />} /> <Form endpoint="api/lead/" /> </React.Fragment> ); const wrapper = document.getElementById("app"); wrapper ? ReactDOM.render(<App />, wrapper) : null; package.json { "name": "amazona_project", "version": "1.0.0", "main": "index.js", "scripts": { "dev": "webpack --mode development ./amazona/frontend/src/index.js --output ./amazona/frontend/static/frontend/main.js", "build": "webpack --mode production ./amazona/frontend/src/index.js --output ./amazona/frontend/static/frontend/main.js" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.1.6", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", "babel-loader": "^8.0.4", "babel-plugin-transform-class-properties": "^6.24.1", "prop-types": "^15.6.2", "react": "^16.6.3", "react-dom": "^16.6.3", "webpack": "^4.25.1", "webpack-cli": "^3.1.2" }, "dependencies": {}, "description": "" } I'm sure the problem has something to do with the syntax, but I dont understand which part is wrong in my code. I would really appreaciate the help, thanks in advance. -
What does database connection limit mean?
I'm using Django with a Postgres database from heroku. The heroku database has a "connection limit of 20". I don't understand what this means. How is a connection defined? Every time a user visits my site I will get some stuff of the database. Is this already a connection because my website needs to connect to the database to get this data? And what happens if the total number of connections is reached? Does the website still work? -
where should the codes for user management be located in django?
I'm a bit confused with where do I put the codes for the user authentication stuff (views, templates, urls). should I create another just for user management? or should this be included in an app? if yes, do all apps need to have its own authentication codes? or should this be included in the main project?