Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to carry out changes to unique_together constraint from one set of model fields to another in Django
In my Django project I have the following model: class TenderOrigin(models.Model): doc_type = models.CharField(max_length=2, ...) doc_short_txt = models.CharField(max_length=150, ...) create_date = models.DateField(default=timezone.now, ...) port_grp = models.ForeignKey(PortGroup, on_delete=models.CASCADE, null=True, ...) # frt_grp = models.ForeignKey(FrtGroup, on_delete=models.CASCADE, null=True, ...) locn_from = models.ForeignKey(Plant, on_delete=models.CASCADE, ...) tender_number = models.CharField(max_length=150, null=True,...) tender_date = models.DateField(null=True, ...) class Meta: ordering = ['locn_from__LocName'] # unique_together = [['frt_grp', 'locn_from', 'tender_date'],] # Original constraint unique_together = [['port_grp', 'locn_from', 'tender_date'],] # New constraint being defined As noted (against the unique constraints' defn.) above, I am trying to change the original unique_together constraint to the new one (using field port_grp). The change is necessitated by a new field (port_grp) that is being added to the model, while field frt_grp is being removed. However, while migrating I am getting following error message: ... ... Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) ... ... File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: matmovt_tenderorigin.port_grp_id, matmovt_tenderorigin.locn_from_id, matmovt_tenderorigin.tender_date Is it possible to change unique_together constraint as defined for one set of fields, to another (without deleting existing data)? -
Error in Celery : OperationalError('could not translate host name "<my_db_server_url>" to address: System error\n',)
The error occurs on my Celery instance alone, my django app being fine when accessed through shell or browser. Obviously the issue is a DNS not being resolved. Except that when I ping my db server from the application server, the host is resolved with no problem. I don't see any network related error in any system log on the application server. Weirdly another error appears in Celery : OSError(24, 'Too many open files') I've checked several times and the ulimit is not reached, also I make sure to close every resource in my code after use. I've restarted the Celery instance, the app was fine for a couple of days only. -
How to make a Django view expect the CSRF token to be in the headers, not in the cookie?
My Django backend and React frontend are decoupled, running on localhost:8000 and localhost:3000 respectively. I am trying to make this POST request from the frontend: async function test() { let url = 'http://127.0.0.1:8000/test' let token = await get_csrf_token() // here I am fetching the token from another backend endpoint. It works fine. let response = await fetch(url, { method: 'POST', headers: { 'X-CSRFToken': token, }, credentials: 'include', }) let response_text = await response.text() console.log(response_text) } test() to this endpoint: def test(request): return HttpResponse('IT IS WORKING') but I get Forbidden (CSRF cookie not set.): /test every time, unless I decorate the endpoint with @csrf_exempt, which I am not willing to do as I want to keep the CSRF protection. My guess is that Django expects the CSRF token to be in the cookies, and not in the headers. But my request is cross domain, so I cannot take advantage of cookies here. Is that right? How can I fix this and possibly make Django accept the token from the headers I am providing? Furthermore, I am using django-cors-headers middleware and also made sure that my settings.py contains all the right CORS/CSRF settings: import os # Build paths inside the project like … -
How can I integrate autogenerated database model diagrams into admin documentation interface?
I'm using graph_models from django-extensions to generate diagrams from a Django application's database models. I would like to integrate the diagram into the documentation of the admin interface (django.contrib.admindocs). Is there a way to integrate the diagrams (preferably by executing a streamline command comparable to python manage.py collectstatic)? -
Django: URL with multiple Variables
I'm having difficulties using RegEx with Django-Urls. Given a string and two integers, s, i1, i2, i want to create the following url: /s/?pagem=i1&pagec=i2. Then, from inside of the correnspoding template, i want to create an href, redirecting to the page given s, i1, i2. How do i do that? I tried: in urls.py: re_path(r'^<str:s>/(?P<pagem>[0-9]&<pagec>[0-9])/$', view, name='chat-explicit-pag'), in template:<a href="{% url 'chat-explicit-pag' s i1 i2 %}", which gives: Reverse for 'chat-explicit-pag' with arguments '('39_41', 1, 1)' not found. 1 pattern(s) tried: ['chat/<str:s>/(?P<i1>[0-9]&<i2>[0-9])/$']. Thanks for your help! -
How to start Django from php file that is using Apache2?
I know i should have created my entire application in Django.But i was'nt much into Web Technology. I created a php file(in apache) in which i have two iframes .In the first iframe i am accepting values from user and in the second iframe i have to use those values and apply machine learning algorithm in python to predict a value.I have Django installed and it shows the default page in the browser.But when i give the path 127.0.0.1:8000 in my second iframe i throws an error " localhost refused to connect" . If its not possible how can i apply machine learning in php so that i don't have to use Django ?enter image description here -
I want to show the topic title in the website template url link on django 3
I want to show the topic title in the website template url link on django 3. currently opening the topic id number. for example : http://localhost:8000/detay/4 for example : http://localhost:8000/detay/2 for example : http://localhost:8000/detay/1 but I want to do it this way for example : http://localhost:8000/detay/1/this-is-topic-title or for example : http://localhost:8000/detay/3/this-is-topic-title . . . views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import * # Create your views here. def index(request): girdiler = Deneme1Model.objects.filter(yuklemeTarihi__lte=timezone.now()).order_by('-yuklemeTarihi') context ={ 'girdiler':girdiler } return render(request, 'deneme1Uygulama/index.html', context) def ekle(request): return render(request, 'deneme1Uygulama/ekle.html') def detay(request, pk): girdiler = Deneme1Model.objects.filter(pk=pk) context ={ 'girdiler':girdiler } return render(request, 'deneme1Uygulama/detay.html', context) def sayfaYok(request): return render(request, 'deneme1Uygulama/404.html') urls.py from django.urls import path from .import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.index, name='index'), path('ekle/', views.ekle, name='ekle'), path('detay/<int:pk>', views.detay, name='detay'), path('404/', views.sayfaYok, name='sayfaYok'), ] urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models from django.utils import timezone # Create your models here. class Deneme1Model (models.Model): baslik = models.CharField(max_length=50, verbose_name='BAŞLIK') aKaydi = models.CharField(max_length=50, verbose_name='A KAYDI') dosyaYukle = models.FileField(upload_to='media', verbose_name='DOSYA YÜKLE') yuklemeTarihi =models.DateTimeField(default =timezone.now) yayinKontrol = models.BooleanField(default=True) def __str__(self): return self.baslik detay.html {% block content %} <div class="row"> {% if girdiler %} {% for girdi … -
Create a new Object from another model in django
I am new to Django V3.0.4 I use the main Django Tutorial from Django website in the models, I have a model that name is Choice class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200, blank=False) and i create a new model that is name Votes. class Votes(models.Model): choice=models.ForeignKey(Choice,on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now_add=True, auto_now=False) I want to add a function Choice model to add a new vote. What can I do? -
Unable to runserver when I close my SSH connection with AWS EC2
Hope anyone with these areas of expertise can help me. Basically, I am trying to run my Django project inside the EC2 instance in Amazon Web Service. I have placed the files and tried to run the server with python3 manage.py runserver 0.0.0.0:8000 The steps I used to configure my EC2 is by referring to this website: https://medium.com/saarthi-ai/ec2apachedjango-838e3f6014ab. I followed all the steps and I was able to deploy my project. However, once I close my SSH connection, I won't be able to access the website anymore. Is there a solution to this? Regards, YX -
Change Document 'objects' property to 'query'
I'm trying to change the document 'objects' property to 'query'. It's more intuitive since one is querying the database. Like; Collection.query.find() Instead of; Collection.objects.find() I have tried setting a query attribute to my Collection model like; class Collection(Document): def __setattr__(self, key, objects): self.__dict__['query'] = self.objects But on checking the type it returns a class of the QueryManager instead of Queryset like; >>>print(type(Collection.query)) <'class' mongoengine.queryset.queryset.QueryManager > Instead of; >>>print(type(Collection.query)) <'class' mongoengine.queryset.queryset.Queryset > Could someone offer a solution ? -
Django/Nginx/Gunicorn/Supervisor: how restart application to restart to take into account internationalization?
I am newbie in dev and Django and it is my first deployement I use for the first time Django/Nginx/Gunicorn/Supervisor and my site is available but internationalization is not applied I run django-admin compilemessages but it did not change anything I think it could be because changes have not been taking and maybe I shloud restart application I try sudo restart myapplication but it is not a valid command -
How do I create user specific page with Django?
so I've just started studying Django, and ran into a problem. I'm trying to create a user-specific page, in which if user logs in and inputs his/her info, the info is displayed on the screen, dynamically of course. So let me show you the codes I wrote. Here's models.py class UserInfo(models.Model): authuser = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'userinfo', null=True, default=None) name = models.CharField(max_length=50) introduction = models.CharField(max_length=100) And here's views.py @login_required(login_url="/register") def main(response): thisUser = # I have no idea on which code to write here. return render(response, 'main.html', {'thisUser' : thisUser}) And here's the html file, main.html {% extends 'base.html' %} {% block content %} {{thisUser.name}} {{thisUser.introduction}} {% endblock %} So this is what I've done so far. I have completed all the registration/login/logouts, as well as the forms for letting users input their info(name, introduction). And the next step I'm trying to take is this user specific page, but I have no idea on how to create it. I would very much appreciate your help. Thanks. :) -
Loading GPX files from AmazonS3 with Google-Maps-APIv3 only works locally, but not on a deployed site (Heroku)
I'm trying to apply Google Maps API (v3) on my site, which is deployed on Heroku. The map is populated with a given GPX file, provided by JS/Ajax. The GPX file is stored on AmazonS3. ( I don't think that it's matter, but note the the site is built with Django, and the GPX file is a FileField of the relevant model ). It works very well locally (local ip), but the map is not loaded at the deployed site. I couldn't track any related error on the server logs, e.g. wrong key, etc. Following is the relevant code snippet: <div id="map" style="width: 50%; height: 50%;"></div> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDcpiBRZzRs_JMfvLmIWGNI8SxSanufbUo&callback=initMap" type="text/javascript"></script> <script> function loadGPXFileIntoGoogleMap(map, filename) { $.ajax({url: filename, dataType: "xml", success: function(data) { var parser = new GPXParser(data, map); parser.setTrackColour("#ff0000"); // Set the track line colour parser.setTrackWidth(5); // Set the track line width parser.setMinTrackPointDelta(0.001); // Set the minimum distance between track points parser.centerAndZoom(data); parser.addTrackpointsToMap(); // Add the trackpoints parser.addRoutepointsToMap(); // Add the routepoints parser.addWaypointsToMap(); // Add the waypoints } }); } $(document).ready(function() { var mapOptions = { zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map"), mapOptions); loadGPXFileIntoGoogleMap(map, "{{ object.gpx_file.url }}"); }); </script> Here is the corresponding snapshots: Can you please … -
Elasticsearch : Should function not working in must
I want to use nested must block within should block in elastic search. { "query": { "bool": { "should": [], "must_not": [], "must": [{ "bool": { "should": [{ "wildcard": { "custom_search": { "boost": 1.0, "value": "e456799p*", "rewrite": "constant_score" } } }] } }, { "match": { "is_deleted": { "query": false } } }] } } } The above query is working for me but when I am adding one more condition in should block than it doesn't work for me. This is "OR" condition, if one condition is satisfied then it is not necessary that other conditions should also satisfy. For Example: - TRUE OR FALSE ==> TRUE result. { "query": { "bool": { "should": [], "must_not": [], "must": [{ "bool": { "should": [ { "bool": { "must": [{ "nested": { "path": "messages", "query": { "bool": { "must": [], "must_not": [], "should": [] } } } }] } }, { "wildcard": { "custom_search": { "boost": 1.0, "value": "e456799p*", "rewrite": "constant_score" } } } ] } }, { "match": { "is_deleted": { "query": false } } }] } } } Please give me the best solutions for it. Thanks in Advance. -
Sending HTML Template via email django
Sorry I just have a question on a previously answered question but couldn't comment cause my reputation isn't high enough. :P For this answer where should I place my html that I'd like to send via email, that they called "mail_template.html"? -
<ForeignKey> is not JSON serializable Django App
I am receiving the error is not JSON serializable when I attempt to do the below in my view. Could someone please assist - I am completely unfamiliar with what this means. views.py .... form = PackingListForm(request.POST) .... object = PackingListDocuments.objects.get(pk=instance_key) #get the object object.Reference_Number = form.cleaned_data.get('Reference_Number') #this is creating the error Reference_Number is a foreignkey to the Shipment model which I suppose is why I'm getting this error but I have no idea why or what I might do differently models.py class Shipment(models.Model): Reference_Number = models.CharField(max_length=100) Ultimate_Consignee = models.CharField(max_length=100) class PackingListDocuments(models.Model): Reference_Number = models.ForeignKey(Shipment, null=True, default=None) PackingListDocument = models.FileField(upload_to='media') forms.py class PackingListForm(forms.ModelForm): class Meta: model = PackingList fields = ['Exporter', 'Consignee', 'Reference_Number', ...] -
How to use PUT method to create object in Django
How to use PUT method for creating an object on particular id if no object is available on that id in Django Rest Framework? -
Django UpdateView teamplate_name_suffix is not working
I have the following code views.py class PageCreate(CreateView): model = Page fields = ['title', 'content', 'order'] success_url = reverse_lazy('pages:pages') class PageUpdate(UpdateView): model = Page fields = ['title', 'content', 'order'] teamplate_name_suffix = '_update_form' def get_success_url(self): return reverse_lazy('pages:update', args=[self.object.id]) + '?ok' page_form.html {% extends 'core/base.html' %} {% load static %} {% block title %}Crear página{% endblock %} {% block content %} {% include 'pages/includes/pages_menu.html'%} <main role="main"> <div class="container"> <div class="row mt-3"> <div class="col-md-9 mx-auto"> <div> <form action="" method="post">{% csrf_token %} <table> {{ form.as_table }} </table> <br> <input type="submit" value="Crear página" /> </form> </div> </div> </div> </div> </main> {% endblock %} page_update_form.html {% extends 'core/base.html' %} {% load static %} {% block title %}Actualizar página{% endblock %} {% block content %} {% include 'pages/includes/pages_menu.html'%} <main role="main"> <div class="container"> <div class="row mt-3"> <div class="col-md-9 mx-auto"> <div> {% if 'ok' in request.GET %} <p style="color:green;"> Pagina editada correctamente <a href="{% url 'pages:page' page.id page.tittle|slugify %}"></a> </p> {% endif %} <form action="" method="post">{% csrf_token %} <table> {{ form.as_table }} </table> <br> <input type="submit" value="Actualizar página" /> </form> </div> </div> </div> </div> </main> {% endblock %} urls.py path('create/', PageCreate.as_view(), name='create'), path('update/<int:pk>/', PageUpdate.as_view(), name='update') The problem is that when i go to the update page it's loading the … -
Django get foreign key model type for OneToMany field
So in Django 1.10 I am trying to extract the model for a specific attribute that is a foreign key in a one-to-many relationship with the parent class. For example: class some_class(models.Model): some_text = models.TextField(blank=True, null=True) class another_class(models.Model): a_field = models.TextField(blank=True, null=True) many = models.ForeignKey(some_class, models.SET_NULL, db_column='some_class_id', related_name='another_class_things', blank=True, null=True) If I was to do: the_class = some_class._meta.get_field('another_class_things').rel.to I get the error: 'ManyToOneRel' object has no attribute 'rel' This works alright when there is a one-to-one relationship, however it doesn't work for one-to-many relationships. What is an alternative to get the model of the attribute? (ie: return 'another_class' in the above situation) -
Deploying Django project on Apache/Ubuntu
I'm trying to deploy my Django project on Apache but it's very hard for me. I'm going to explain what I did these days and maybe you can see the fail. 1. Annotations: My project is located in james/DjangoRFV and I don't have a virtual env. I'm not sure if this is important, but this django project is in a remote server that I'm acceding using ssh, specifically port 2222. What I have it's an ip direction, like 172.33.52.8 (not real). 2. Deploying on apache: First I create the virtual host file like this, <VirtualHost *:80> ServerAdmin admin@DjangoRFV.localhost ServerName DjangoRFV.localhost ServerAlias www.DjangoRFV.localhost DocumentRoot /home/james/DjangoRFV ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/james/DjangoRFV/static <Directory /home/james/DjangoRFV/static> Require all granted </Directory> Alias /static /home/james/DjangoRFV/media <Directory /home/james/DjangoRFV/media> Require all granted </Directory> <Directory /home/james/DjangoRFV/DjangoRFV> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess DjangoRFV python-path=/home/james/DjangoRFV python-home=/home/james/DjangoRFV/env WSGIProcessGroup DjangoRFV WSGIScriptAlias / /home/james/DjangoRFV/DjangoRFV/wsgi.py </VirtualHost> Now I enable the virtual host file. cd /etc/apache2/sites-available sudo a2ensite djangoRFV.conf Some permissions sudo ufw allow 'Apache Full' Check syntax errors: sudo apache2ctl configtest 3. Modify wsgi.py: import os, sys #path a donde esta el manage.py de nuestro proyecto Django sys.path.append(‘/home/james/DjangoRFV/’) #referencia (en python) desde el path anterior al fichero settings.py #Importante hacerlo … -
Django nginx uwsgi can' work in linux normal user
I successful run Django nginx uwsgi in root few days ago. But I fail in normal user today. The error message follow this: detected binary path: /home/disney/IP_lookup/IP_lookup_venv/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! chdir() to /home/disney/IP_lookup/mysite your processes number limit is 128426 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) error removing unix socket, unlink(): Permission denied [core/socket.c line 198] bind(): Address already in use [core/socket.c line 230] I already read this article: Could not start uwsgi process But I don't know how to change my uwsgi.ini. my uwsgi.ini: [uwsgi] # Django-related settings # the base directory (full path) chdir = /home/disney/IP_lookup/mysite # Django's wsgi file module = mysite.wsgi # the virtualenv (full path) home = /home/disney/IP_lookup/IP_lookup_venv # process-related settings # master master = true # maximum number of worker processes processes = 2 # the socket (use the full path to be safe socket = /home/disney/IP_lookup/mysite/mysite.sock # ... with appropriate permissions - may be needed # chmod-socket = 777 uid = www-data gid = www-data # clear environment on exit vacuum = true -
How do I use a ModelChoiceField in the Django Admin
I am trying to figure out how to use a ModelChoiceField to get the select options from the database and display a field as a select box (single select) in the Django admin area on the model form page. The code I have in the modelform is shown below but the field is showing as a text field and obviously isn't populated with any of the options (yes they exist in the database SomeObjectHere table). I also need to know how to do the same with a multiple choice select (more than one selection) from .models import * from django import forms from django.forms import ModelForm, Textarea, RadioSelect, CheckboxInput,CheckboxSelectMultiple, TextInput, Select from references.models import * class MyModelForm(ModelForm): PropertyName = forms.ModelChoiceField(queryset=SomeObjectHere.objects.all()) class Meta: model = MyModel fields =('__all__') # exclude = ('',) widgets = { 'PropertyNameHere' : Select() } def __init__(self, *args, **kwargs): super(MyModelForm, self).__init__(*args,**kwargs) The Admin.py looks like this: class MyModelAdmin(admin.ModelAdmin): not really sure what i need to do here. I'm using grapelli which is using the media class class Media: js = [ '/static/grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js', '/static/grappelli/tinymce_setup/tinymce_setup.js', ] -
how to represent equivalent java class in python
I have a class relationship in java like this: class A (){ private string var1 } class B (){ private string var2 } class C (){ private string var3 List<A> aList = new ArrayList<A>(); List<B> bList = new ArrayList<B>(); } class D (){ private string varD List<C> cList = new ArrayList<C>(); } how do I represent such a relationship between class in python ?? -
Why isn't django.contrib.auth.authenticate() working here?
I'm writing a simple (for now) Django app. I'm having trouble with authentication: I'm trying to use all of the out-of-the-box components, and both in the app itself and in tests, I can't authenticate users. So, for example, here's a test that fails: from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.test import TestCase [...] class UserTestCase(TestCase): def setUp(self): self.testu = User(username="thename", password="thepassword", first_name="thefirstname") self.testu.save() def testAuthenticate(self): u = authenticate(username="thename", password="thepassword") self.assertEqual(u.first_name, "thefirstname") I get an AttributeError: 'NoneType' object has no attribute "first_name". I think this is because authenticate() is returning None (representing that there is no such user). This fails whether or not I include the line "self.testu.save()". I have other tests that pass, so I don't think the problem is with the test infrastructure. I can successfully create users and retrieve their information from the database. The only mention of User in models.py is: from django.contrib.auth.models import User I've read through a lot of documentation but can't figure out what's going on. Can anyone help? Thanks in advance. -
Django Rest framework serialier for categorywise data
I have a model named JobTite: class JobTitle(BaseModel): """ Store job titles used in benchmarking """ benchmark_role = models.ForeignKey( BenchmarkRole, on_delete=models.SET_NULL, related_name='job_titles', null=True, blank=True ) name = models.TextField() description = models.TextField(null=True, blank=True) count = models.IntegerField( validators=[MinValueValidator(0)], null=True, blank=True ) class Meta: constraints = [ models.UniqueConstraint(fields=['benchmark_role', 'name'], name='unique_job_title') ] def __str__(self): return "{}-{}".format(self.benchmark_role, self.name) I need to get the top 10 JobTtles for each benchmark_role and return a JSOn something like this: [{"benchmark_role_1": [ {name: "ABC", desc: 'DESC', count: 9}, {name: "def", desc: 'DESC', count: 6}, {name: "XR", desc: 'DESC', count: 4}, {name: "AS", desc: 'DESC', count: 2}, {name: "RE", desc: 'DESC', count: 3}, {name: "Q", desc: 'DESC', count: 1}, {name: "QW", desc: 'DESC', count: 0}, {name: "AS", desc: 'DESC', count: 0}, {name: "W", desc: 'DESC', count: 0}, {name: "EW", desc: 'DESC', count: 0}, ]}, {"benchmark_role_2": [ {name: "AAC", desc: 'DESC', count: 8}, {name: "dAf", desc: 'DESC', count: 6}, {name: "QW", desc: 'DESC', count: 4}, {name: "AS", desc: 'DESC', count: 2}, {name: "QE", desc: 'DESC', count: 3}, {name: "Q", desc: 'DESC', count: 1}, {name: "QW", desc: 'DESC', count: 0}, {name: "AS", desc: 'DESC', count: 0}, {name: "W", desc: 'DESC', count: 0}, {name: "EW", desc: 'DESC', count: 0}, ]}, ...] My curent …