Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does HTTP Request result in OPTIONS rather than POST
I'm trying to do a POST request with some JSON data from an HTML page to a Django server running on localhost. Whenever I hit the button to do the POST, it results in 'OPTIONS' rather than a 'POST' I tried changing the headers for Access Control but that was to no avail. This is my javascript method. function doPost() { document.getElementById("confirmation").innerHTML = "Your order is being made."; var xhr = new XMLHttpRequest(); var url = "http://127.0.0.1:8080/app/newitem/"; xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("Access-Control-Allow-Origin", "*"); xhr.setRequestHeader("Access-Control-Max-Age", "600") xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { var json = JSON.parse(xhr.responseText); } }; var data = JSON.stringify({"name": "Sid", "email": "testemail@testabc.com", "price": "44.99"}); xhr.send(data); } When this function was called, I expected the Django server to produce a message indicating the 'POST' occurred, instead I get [20/Sep/2019 21:36:45] "OPTIONS /app/newitem/ HTTP/1.1" 200 169 -
How to relate two models of existing database tables with specific key link?
I'm converting an excel document into a web application. I'm using Django REST as the backend, and Angular as the frontend. I have an legacy database (read-only) that has 3 tables that I want to join together to get the needed data. Basically, I'm using this to auto-populate a form. So, the user will enter a known meter number into the form, and then click a button to pull the other related information into the form - minimizing data entry. Simplified database tables and columns MeterNumber account_number meter_number Customer account_number (related to MeterNumber) mailing_address ServiceLocation account_number (related to MeterNumber) service_address So, as you can see, these tables all have the same account_number column. I'd like to be able to make a REST call to something like: server/get_data?meter_number=123456 And then the JSON response would be something like: { "account_number": 111111, "meter_number": 123456, "customer": [ { "account_number": 111111, "mailing_address: "PO Box 1234, WA 97545" } ], "service_location": [ { "account_number": 111111, "service_address: "50 Elm St, WA 85426" } ] } And this response would be used to populate the form. But how to I create these relationships based on the account_number field? Also, this database is read-only. Models: class MeterNumber(models.Model): bi_acct = … -
Django admin not showing records while still showing number
I have a model with a Foreign Key without a db_constraint. I do this so I can insert values that may not point to the foreign table. I was able to import values properly. In the Django admin, if I look at the model type that contains the constraintless foreign key, I can not see the models, but I do see a certain number of models exist. This is my code class HlaType(models.Model): specimen = models.ForeignKey(SpecimenInfo, on_delete=models.CASCADE, verbose_name="Specimen", related_name="hlatype", db_constraint=False) allele_key = models.CharField(max_length=5, db_index=True) allele = models.CharField(max_length=50, blank=True, db_index=True) class Meta: constraints = [ models.UniqueConstraint(fields=('specimen', 'allele_key'), name='targets_hlatype_unique_specimen_and_key') ] class HlaTypeAdmin(ImportExportMixin, admin.ModelAdmin): raw_id_fields = ["specimen"] list_display = ('specimen', 'allele_key', 'allele') resource_class = HlaTypeResource list_per_page = 200 class HlaTypeResource(ModelResource): specimen = Field(attribute='specimen', column_name='specimen_id', widget=HlaWidget(SpecimenInfo, 'pk')) allele_key = Field(attribute='allele_key', column_name='allele_key') allele = Field(attribute='allele', column_name='allele') class Meta: model = HlaType import_id_fields = ('specimen', 'allele_key') skip_unchanged = True fields = ('id', 'specimen', 'allele_key', 'allele') Any idea how to remedy this? -
List of model fields with missing values nicely formatted in Django template
I'm trying to make a view in Django to list each entry in a model and any of the fields that are missing values. The template is a table: one column is a specific field and the other column is a list of the fields with missing values. I have a working version, but the missing fields are just strung together, and I'd like to have them nicely formatted with commas in between. #models.py class exif(models.Model): image = models.ForeignKey('image', on_delete=models.CASCADE, blank=False, null=False) filename = models.CharField(max_length=100, blank=True, null=True) artist = models.CharField(max_length=100, blank=True, null=True) copyright = models.CharField(max_length=100, blank=True, null=True) keywords = models.CharField(max_length=100, blank=True, null=True) caption = models.CharField(max_length=100, blank=True, null=True) comment = models.CharField(max_length=100, blank=True, null=True) ... #views.py def exif_export(request): exif_records = serializers.serialize("python", exif.objects.all()) return render(request, 'exif_export.html', {'exif_records': exif_records}) #exif_export.html <table> <tr> <th>File</th> <th>Missing Exif Fields</th> </tr> {% for record in exif_records %} <tr> <td> {% for field, value in record.fields.items %} {% if field == 'filename' %} {{ value }} {% endif %} {% endfor %} </td> <td> {% for field, value in record.fields.items %} {% if not value %} {{ field }}, <!-- This comma makes a trailing comma at the end of the list --> {% endif %} {% endfor %} … -
How to use components of an admin page in another page?
I have customized the "change_form_template" of an object in my Django admin panel. I want to add a table in my new page but I don't want to code the functionalities of the table from the scratch. I would like to know is there any way to some how use the "change_list_template" page table and its functionalities in my new page? -
Problem redirecting to file from post link
I am having trouble with redirecting the link to the proper file when a link inside the post is clicked. The file is stored in a media and can be viewed from localhost/media/filename.pdf with no issues. Inside of post_detail.html <a href="/media/{{ object.post_files }}">{{ object.post_files }}</a> My urls.py urlpatterns = [ path('', PostList.as_view(), name='forum-home'), path('about/', views.about, name='forum-about'), path('post/new/', PostCreate.as_view(), name='post-create'), path('post/<int:pk>/', PostDetail.as_view(), name='post-detail'), path('post/<int:pk>/update/', PostUpdate.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDelete.as_view(), name='post-delete'), path('post/comment/', CommentCreate.as_view(), name='add_comment_to_post'), ] I'm assuming this is a path error because the error is:http://localhost:8000/post/4/media/filename.pdf This would mean it is checking staying with in post. -
Django: How to check a Form with a m2m relation object already exists or is “unique_together”?
I am testing forms and nesting models in django. In my Project a Person can enter departure, arrival (city names) and choose a weekly day (Mon-Fri). Maybe he drives every “Tuesday” from Amsterdam to Paris. I wanted this constellation to be unique – just for fun. So If another user enters the same route the relation should be linked to the same Car.object. Models.py class Person(models.Model): name = models.CharField(max_length=255, blank=False, unique=True) route = models.ManyToManyField('Car') def __str__(self): return self.name class Car(models.Model): name = models.CharField(max_length=255, blank=False, unique=True) weekdays = models.ForeignKey('Week', null=True, blank=False, on_delete=models.SET_NULL) departure = models.CharField(max_length=255, blank=False) arrival = models.CharField(max_length=255, blank=False) class Meta: unique_together = ['weekdays', 'departure', 'arrival'] # --- Unique combination def __str__(self): return self.name class Week(models.Model): day = models.CharField(max_length=255, blank=False, unique=True) def __str__(self): return self.day views.py class RouteCreateView(CreateView): model = Person template_name ="testa/create_route.html" form_class = RouteForm success_url = reverse_lazy('testa:testa_home') def form_valid(self, form): return super().form_valid(form) forms.py class RouteForm(forms.ModelForm): # --- apply ChoiceField day = forms.ModelChoiceField(queryset=None) car_name = forms.CharField() departure = forms.CharField() arrival = forms.CharField() class Meta: model = Person fields = [ 'name' ] def __init__(self, *args, **kwargs): super(RouteForm, self).__init__(*args, **kwargs) self.fields['day'].queryset = Week.objects.all() def save(self, commit=True): personData = super().save(commit) data = self.cleaned_data carData = Car(name=data['car_name'], weekdays=data['day'], departure=data['departure'], arrival=data['arrival']) if commit: … -
How do I add image to object in Python?
Seemingly trivial question, but I'm stuck. I'm trying to add add a photo to a model's ImageField when I create the model. But I don't know how to specify the photo. Do I specify the path, or a photo object? class MyModel(models.Model): img = models.ImageField() # I tried these, none works from PIL import Image MyModel.objects.create(img='img.jpg') MyModel.objects.create(img=Image.open('img.jpg')) MyModel.objects.create(img=open('img.jpg', 'r')) MyModel.objects.create(img=open('img.jpg', 'w')) -
How to select and deselect options if multiselect option coming from ajax response
<div class="content-section"> <form method="POST" id="moviesForm" ajax_load_cast="{% url 'ajax_load_cast' %}" novalidate enctype="multipart/form-data" > {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"></legend> <div class="form-group"> <label for="id_cast" class="col-form-label requiredField">Cast<span class="asteriskField">*</span> </label> <div class=""> <input type="text" name="cast" value="" maxlength="50" class="textinput textInput form-control" required="" id="id_cast"> <select id="add_cast2" multiple style="width:100%" ></select> </div> </div> <div id="" class="form-group"> </div> </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> {% block js%} <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> var ajaxResult=[]; $("#id_cast").keyup(function () { var url = $("#moviesForm").attr("ajax_load_cast"); var text_input = $('#id_cast').val(); $.ajax({ url: url, data: { 'text_input': text_input }, success: function (data) { $("#add_cast2").html(data); } }); }); </script> {% endblock js%} {% endblock content %} I am implementing a django multiselect option formField with basic html and ajax request so that it filters results before showing all the results. But I don't know how to implement select and deselect with the ajax response that brings multiselect options from database. With each response it deselects the selected options. -
Create several instances out of a related model in Django
In university as a part of a project we have to develop a liga system with Django. I have my basic app running and also my models are already set up. from django.db import models from datetime import datetime # Create your models here. class Player(models.Model): vorname = models.CharField(max_length=30) nachname = models.CharField(max_length=50) created_on = models.DateTimeField(auto_now_add=True) email = models.EmailField() class Liga(models.Model): name = models.CharField(max_length=50) participants = models.ManyToManyField(Player) created_on = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=False) is_completed = models.BooleanField(default=False) class Game(models.Model): liga = models.ForeignKey(Liga, on_delete='DO NOTHING') player1 = models.CharField(max_length=100) player2 = models.CharField(max_length=100) score_pl1 = models.IntegerField(blank=True) score_pl2 = models.IntegerField(blank=True) is_completed = models.BooleanField(default=False) completed_on = models.DateTimeField(auto_now_add=True) Now when I've created a new liga in the admin area I want Django to automatically create the Game instances (wich could be several). I've tried several different ways to do that but couldn't fix that problem. -
How to install OS dependent packages in Zappa (wkhtmltopdf)
I am using Weasyprint to convert html to pdf in my code. Everything runs fine locally. Weasyprint depends on wkhtmltopdfpackage. This package needs binaries installed on system with sudo apt install wkhtmltopdf which is dependancy else I get No wkhtmltoimage executable found: "b''" How can I install this binary required in zappa environment as this is OS depedent package? -
Pass html form action parameters to django view
I'm making an app to save mileage of a truck per state. I've already passed required data to my view, and then I thought to change my urls to more logical. And after that I faced a problem. I don't know what should be instead of "unit.unit_number", and it is required, in my html file for it to work correctly. I didn't find anything that could explain how to deal with it. If I try to access mywebsite.com/core/units/1/locations/add/ I get next error message: "NoReverseMatch at /core/units/1/locations/add/" But if I put just a number (1 for example) instead of "unit.unit_number" it loads the page normally, but I get an error after trying to post the data: "TypeError at /core/units/1/locations/add/ _reverse_with_prefix() argument after * must be an iterable, not int" <form action="{% url 'Core:unit_add_location' unit.unit_number %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="container"> <div class="inner-container border-full"> <button type="button" class="button button-normal" onclick="AddRow()">Add</button> <input type="submit" class="button button-submit" name="count-ifta" value="Save"> <div class="inner-container border-top-bottom"> <table id="myTable" name="state-miles-data"> <thead> <th class="text-blue">State</th> <th class="text-blue">Miles</th> </thead> </table> <br> </div> </form> <button type="button" class="button button-normal" onclick="AddRow()">Add</button> </div> </div> def unit_data(request, unit_number): return HttpResponse(unit_number) def unit_add_location(request, unit_number): if "GET" == request.method: return render(request, 'Core/add_location.html') elif "POST" == request.method: states_request = request.POST.getlist('states') … -
GET http://localhost:8000/add/ Page not found
I've been working on this application using my localhost:8000 for a while now and everything had been working smoothly. However now that I have tried to add a new url: /add/. For some reason it doesn't recognise the URL. I believe maybe there's something wrong with how I've wrote my code but I haven't quite found it. Any help would be great! To provide context I started of in my urls.py file where I created a new path: path('add', views.ProjectCreateView.as_view(), name='add'), I then moved over to my views.py file and imported the CreateView as so: from django.views.generic import CreateView. From there I then created a class for the view: class ProjectCreateView(CreateView): model = Project template_name = 'budget/add-project.html' fields = ('name', 'budget') Following this I then created another file within my budget folder nested in my templates folder. The file name add-project.html. I don't think there's anything wrong with this file but just to guarantee this is how I linked my html file: {% extends 'budget/base.html' %} {% load static %} {% block content %} This is the exact message I get when I run http://localhost:8000/add/ "No Project matches the given query." -
Running celeryd-worker on elastic-beanstalk
I am trying to get celery set up on elastic-beanstalk to run periodic-tasks. I have gotten everything running except for the celeryd-worker on elastic-beanstalk. It deploys fine and it is registering tasks but when I set up a periodic task either in celery.py or through django-celery-beat it doesn't execute. I pulled the logs from EB and got /opt/python/log/supervisord.log ------------------------------------- 2019-09-20 16:32:50,831 INFO spawned: 'celeryd-worker' with pid 712 2019-09-20 16:32:53,929 INFO exited: celeryd-worker (exit status 1; not expected) 2019-09-20 16:32:54,930 INFO gave up: celeryd-worker entered FATAL state, too many start retries too quickly 2019-09-20 16:41:43,327 INFO stopped: celeryd-beat (exit status 0) 2019-09-20 16:41:44,333 INFO spawned: 'celeryd-beat' with pid 1664 2019-09-20 16:41:54,442 INFO success: celeryd-beat entered RUNNING state, process has stayed up for > than 10 seconds (startsecs) 2019-09-20 16:41:54,689 INFO spawned: 'celeryd-worker' with pid 1670 2019-09-20 16:41:57,844 INFO exited: celeryd-worker (exit status 1; not expected) 2019-09-20 16:41:58,847 INFO spawned: 'celeryd-worker' with pid 1676 2019-09-20 16:42:02,037 INFO exited: celeryd-worker (exit status 1; not expected) 2019-09-20 16:42:04,045 INFO spawned: 'celeryd-worker' with pid 1711 2019-09-20 16:42:05,271 INFO stopped: httpd (exit status 0) 2019-09-20 16:42:05,275 INFO spawned: 'httpd' with pid 1717 2019-09-20 16:42:07,241 INFO success: httpd entered RUNNING state, process has stayed up for > … -
How to load master data (stored in DB) in client pages effectively?
I have a web application (built in Angular1.X and Django) that displays 6 product information (master data) stored in database. This information does not change by any transaction or action in my application, but will be referred in processing user actions. In order to increase the speed of my application page load, I’m trying to find an effective method to quickly access these information in different pages. I know the following are a few of the options to access this information every time. 1) Store the product details in local or session storage at client side for every page load and refer those values from that storage memory 2) Make a call to server to get these information as and when required at client side Is there any other option to store these master data at client side file or other means once at the time of production server start up and use that information for every time page loading? -
Django View: Return Queryset in JSON Format
i am trying to make the following view with return JsonResponse() at the end work correctly: def get_data(request): full_data = Fund.objects.all() data = { "test2": full_data.values('investment_strategy').annotate(sum=Sum('commitment')), } return JsonResponse(data) However, I get an error message saying "Object of type QuerySet is not JSON serializable". When I put the above Queryset in a view with return render() at the end: def get_more_data(request): full_data = Fund.objects.all() data = {"test2": full_data.values('investment_strategy').annotate(sum=Sum('commitment'))} return render (request, 'test.html', data) I get the the following result: <QuerySet [{'investment_strategy': 'Buyout', 'sum': 29}, {'investment_strategy': 'Growth', 'sum': 13}, {'investment_strategy': 'Miscellaneous', 'sum': 14}, {'investment_strategy': 'Venture Capital', 'sum': 23}, {'investment_strategy': 'n/a', 'sum': 36}]> So the queryset works fine, I just have no clue how to return the data in proper Json format (which I would need to use the data charts.js) I looked through answers for similar questions such as: TypeError: object is not JSON serializable in DJango 1.8 Python 3.4 Output Django queryset as JSON etc. but could not find a meaningful solution for my problem. Any help would be much appreciated! -
How to fix 'min() arg is an empty sequence' python+couchdb error
I have to do mosaic application in Python using Django and Couchdb, which are kind of new to me, for my studies. In part where I'm trying to do the mosaic, I got ValueError at 'min' function. However I run out of ideas why it is not working. I read the couchdb docs, reach some friends who already know a little python. rgb_of_tile = list(tile.getdata()) rgb_of_tile_list = utils.get_average_rgb_as_list(rgb_of_tile) returned_tiles = get_tiles(rgb_of_tile_list) closest = min(returned_tiles, key=lambda c: ( (rgb_of_tile_list[0] - c['key'][0]) ** 2 +(rgb_of_tile_list[1] - c['key'][1]) ** 2 + ( rgb_of_tile_list[2] - c['key'][2]) ** 2)) Error occurs on variable 'closest', but when I looked at the error I saw that 'returned_tiles'=[ ]. Below is code for that variable. I don't really know why it is not working, as the CouchDB reference-'tiles_url' should work properly def get_tiles(rgb_of_tile_list): rgb_of_tile_start = [x.__sub__(10) for x in rgb_of_tile_list] rgb_of_tile_finish = [x.__add__(10) for x in rgb_of_tile_list] tiles_url = "http://images_db_user:pass@localhost:5984/images/_design/view/_view/new-view?start_key=" + str( rgb_of_tile_start) + "&end_key=" + str(rgb_of_tile_finish) + "&include_docs=true" response = requests.get(tiles_url).json() returned_tiles = response['rows'] return returned_tiles -
Django/DRF - REST API endpoint with query parameter that goes queries multiple endpoints
Hey guys I'm having some trouble trying to architect how this endpoint would work. Currently I would like this endpoint "/nba/players?date=01012016" to work by going two different endpoints for results. Currently my GameDates endpoint returns something similar to {id: 1, home_team_id: 1, away_team_id: 2, date: "1/1/2016"}, {id: 4, home_team_id: 2, away_team_id: 3, date: "1/2/2016"} I want to grab that GameDate_id or it's primary key (in this case id:1) which then gets passed on to a another PlayerStatistic endpoint which will return something like this - {id: 1, game_id: 1, player_id: 1, team_id: 1, points: 20, assists: 10, rebounds: 2}, {id: 2, game_id: 1, player_id: 2, team_id: 1, points: 15, assists: 2, rebounds: 2}, {id: 3, game_id: 1, player_id: 3, team_id: 2, points: 10, assists: 2, rebounds: 20}, {id: 4, game_id: 1, player_id: 4, team_id: 2, points: 5, assists: 1, rebounds: 2} My initial endpoint with the date query would return these four JSON since a player had a game on that date (game_id = 1) from the GameDate endpoint, then that game_id gets used to query the PlayerStatistic endpoint and returns. I know the right method of say overriding the get_queryset function something like - def get_queryset(self): date = self.request.query_params.get('date') … -
Django check if server is already running
I am on Windows, and run my Django server via manage.py runserver 8001. When I have already running server and enter the mentioned command again, it starts another server listening the same (8001) port. What I would like to do is to determine if server is already running and stop the execution of the command, or stop the running server and then run the new server. -
Django cannot get Django user model to work with send_mail
This line in the view breaks: email = User.objects.filter(user=request.user).values_list('email', flat=True) send_mail('subject', 'message','info@site.com', [email[0]]) Here is the error: During handling of the above exception (Cannot resolve keyword 'user' into field. Choices are: email, first_name, last_name, username), another exception occurred: This used to work, but has now broken and have no idea why. The user has been created. This is the base Django model. -
Django and DocxTemplate with MailMerge
How do you pass a document stored in a FileField to DocxTemplate of the mailmerge package when it is hosted externally such as S3 etc. The DocxTemplate takes a path which then passes it to Document object of the python-docx package.... I need to to edit a file stored as a template on S3 with mailmerge to insert content into the merge fields. -
AH01630: client denied by server configuration - Django - Linux
My website is working but it is unable to access the static folder in my project folder. Here is a the configuration for static in my .conf file: Alias static /home/ubuntu/tasktracker/static <Directory /home/ubuntu/tasktracter/static> AllowOverride none Require all granted </Directory> My other sites are up and running using same configuration. But this one is causing the error. Any ideas? -
Django model save operation is truncating decimal field
Django model save operation is truncating decimal field. Sqlite table schema sqlite> .schema core_stock CREATE TABLE "core_stock" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(255) NOT NULL, "code" varchar(20) NOT NULL, "price" decimal NOT NULL, "diff" decimal NOT NULL, "open_price" decimal NOT NULL, "previous_close" decimal NOT NULL, "low52" decimal NOT NULL, "high52" decimal NOT NULL, "last_updated" datetime NOT NULL); CREATE INDEX "core_stock_code_8719e588" ON "core_stock" ("code"); Model class Stock(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=20, db_index=True) price = models.DecimalField(max_digits=19, decimal_places=2) diff = models.DecimalField(max_digits=19, decimal_places=5) open_price = models.DecimalField(max_digits=19, decimal_places=2) previous_close = models.DecimalField(max_digits=19, decimal_places=2) low52 = models.DecimalField(max_digits=19, decimal_places=2) high52 = models.DecimalField(max_digits=19, decimal_places=2) last_updated = models.DateTimeField() objects = DataFrameManager() def save(self, *args, **kwargs): ''' On save, update timestamps ''' self.last_updated = timezone.now() return super(Stock, self).save(*args, **kwargs) def __str__(self): return str(self.code) When I save stock with stock.diff = 2.45478 it saves it as 2.45. How can I store all 5 digits after decimal correctly in DB? -
django 2.2.5 import url from one app to another app
I would like to use the url from products app (products/urls.py) inside of search app url (search/urls.py) to search for items/products using search bar. I've attempted this example on django docs but it's importing a view to url in the same app, and I've also attempted this example but it looks to be a solution for an older version of django but i am using the latest version of django at time time 2.2.5. The error message I am receiving in terminal is coming from search/urls.py: path('', views.ProductListView.as_view(), name='list'), AttributeError: module 'search.views' has no attribute 'ProductListView' I understand search.views does not have an attribute "ProductListView" but, products.views does, which is why i'm trying to import products.views in search/urls.py. products/urls.py from django.urls import path, re_path from .import views app_name = "products" urlpatterns = [ path('', views.ProductListView.as_view(), name='list'), re_path(r'^products/(?P<slug>[\w-]+)/$', views.ProductDetailSlugView.as_view(), name='detail'), ] search/urls.py from django.urls import path from .import views from products.views import ProductListView urlpatterns = [ path('', views.ProductListView.as_view(), name='list'), ] ecommerce/urls.py (main app) from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include, re_path # from products.views import ProductDetailView from .views import home, about, contact urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), path('about/', … -
How to return an image object in django http response?
I am sending emails containing images. I am using html templates for these emails. I want the images to be generated on the fly. Hence, the 'src' in the image tag is a url that makes a REST api call to my app. The images are dynamically created, a publicly accessible URL is created. I want this image to be displayed in the email. But I am not able to figure out how to return this image.