Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django /Python Program Flow and Structure
I am a new developer and have been learning Python and Django. I'm trying to understand the structure and flow behind the scenes and I'm confused by a line of code that I encountered. Well, I'm actually confused by a number of things but this is one specific example. Can someone help me understand the flow of the following code: from django.contrib import admin from .models import Post admin.site.register(Post) When I search the library files in my virtual environment I find a folder called django and inside that folder I find contrib and inside that folder I find admin. I see that that the init.py file in the admin package has import statements that import in * which I understand to be everything in the various modules that are available. When I go digging through the various modules, I find sites.py and inside sites.py I find a "site" variable that is an object that has been instantiated. Here is the snippet of code from the sites.py module: site = DefaultAdminSite() Ok, here is where I'm confused. Looking back at the original code, where does the "register" function get pulled in. I'm accessing a variable that contains an instantiated object from … -
How to separate the servers for heavy task
I have django web application which has heavy commandline task. like python manage.py my_heavy_task Now I have three servers. One is for webserver ,the second is for command python manage.py my_heavy_task and the last one is for relational database. What is the best practice to separate for two servers??(for Relational database is easy to understand). I have idea to upload whole django framework on each server and one is for web and the other is for command. Is this a silly idea??? or is there any tricks?? I am newbee for django, any helps are welcomed. -
I'm not able create virtual environment using virtualenv
C:\Users\NAVEEN\Desktop\Demo>virtualenv venv Traceback (most recent call last): File "c:\users\naveen\appdata\local\programs\python\python38\lib\runpy.py", line 192, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\naveen\appdata\local\programs\python\python38\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\NAVEEN\AppData\Local\Programs\Python\Python38\Scripts\virtualenv.exe__main__.py", line 4, in File "c:\users\naveen\appdata\local\programs\python\python38\lib\site-packages\virtualenv__init__.py", line 3, in from .run import cli_run File "c:\users\naveen\appdata\local\programs\python\python38\lib\site-packages\virtualenv\run__init__.py", line 12, in from .plugin.activators import ActivationSelector File "c:\users\naveen\appdata\local\programs\python\python38\lib\site-packages\virtualenv\run\plugin\activators.py", line 6, in from .base import ComponentBuilder File "c:\users\naveen\appdata\local\programs\python\python38\lib\site-packages\virtualenv\run\plugin\base.py", line 7, in from importlib.metadata import entry_points ModuleNotFoundError: No module named 'importlib.metadata' -
Django unable to set IntegerField on Serializer
I am not a professional Django user, I will try to described this problem as concise as I can. I have a Django Serializer definition: class PrioritisedMarketActionSerializer(serializers.Serializer): marketaction = MarketActionSerializer(required=True) priority = serializers.IntegerField() My objective is to create a list of these serializers objects, after I received through a POST method a list of MarketAction objects. I declare an empty list where to store these objects: output = [] Then, iterating over the received objects: prioritised_ma["marketaction"] = MarketActionSerializer(ma).data prioritised_ma["priority"] = 1 output.append(PrioritisedMarketActionsSerializer(prioritised_ma_clearing).data) The ["priority"] field was set to 1, {int}, for testing purposes. However, when I call: PrioritisedMarketActionsSerializer(prioritised_ma).data I get this strange error: 'int' object has no attribute 'pk' I assume the error is related to the "priority" field, which is the {int} value, but I can not figure it out. Could someone help me please, or give me a hint towards what am I doing wrong here? I would deeply appreciate it. Thank you very much, I wish you a wonderful day! -
Django: how to make the User registration form create another object too
For a school project, we have to make a food delivery platform using django. In the registration form, I have a checkbox to register yourself as a restaurant owner. If this checkbox is checked, I need it to create not only the User but a Restaurant object as well with the restaurant_name the User entered. How can I accomplish this? Below is the HTML code for my reg form: {% extends 'food_cloud/base.html' %} {% load staticfiles %} {% block title_block %} Register {% endblock %} {% block body_block %} <script type="text/javascript"> function dynInput(cbox) { if (cbox.checked) { var restaurant_name = document.createElement("input"); restaurant_name.type = "text"; restaurant_name.name = "restaurant_name"; var div = document.createElement("div"); div.id = cbox.name; div.innerHTML = "Restaurant name: "; div.appendChild(restaurant_name); document.getElementById("insertinputs").appendChild(div); } else { document.getElementById(cbox.name).remove(); } } </script> <div class="jumbotron p-4"> <div class="container"> <h1 class="jumbotron-heading">Register</h1> </div> </div> <div class="container"> <div class="row"> <div class="form-group" > <form role="form" method="post" action="."> {% csrf_token %} <div class="form-group"> <p class="required"><label class="required" for="id_username"> Username:</label> <input class="form-control" id="id_username" maxlength="30" name="username" type="text" /> <span class="helptext"> Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only. </span> </p> <p class="required"><label class="required" for="id_email"> E-mail:</label> <input class="form-control" id="id_email" name="email_address" type="email" /> </p> <p class="required"><label class="required" for="id_password1"> Password:</label> <input class="form-control" id="id_password1" name="password1" … -
Displaying additional attributes of the standard User on the admin page
To the standard User (Django 2.1.5) imported from django.contrib.auth.models I added an additional attribute: from django.contrib.auth.models import User User.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) class Contact(models.Model): user_from = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rel_from_set') user_to = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rel_to_set') created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return '{} follows {}'.format(self.user_from, self.user_to) Does anyone know how to register this attribute ("following" and "followers") on the admin page so that it is displayed there in the subpage "'http://127.0.0.1:8000/admin/auth/user/< int:id >/" -
Django: test TemplateView based views triggered by url pattern?
Say I have the following url path('clients/by_<str:order>', BrowseClients.as_view(), name='browse_clients') and its corresponding view @method_decorator(login_required, name='dispatch') class BrowseClients(TemplateView): template_name = "console/browse_clients.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['clients'] = Client.objects.filter( owner=self.request.user.id).order_by(self.kwargs["order"]) context['form'] = AddClientForm() return context How can I test what is in the context? class TestBrowseClientsView(TestCase, GeneralViewTest): fixtures = ['users.yaml', 'clients.yaml'] def setUp(self): self.request = RequestFactory().get('/console/clients/by_inscription') self.request.user = User.objects.get(pk=1) def test_return_client_ordered_by_inscription_date(self): view = BrowseClients() view.setup(self.request) context = view.get_context_data() Naively, I thought that view.setup(self.request) would "feed" .get_context_data() with the relevant kwargs based on the pattern found in self.request. But it does not seem to be the case. ====================================================================== ERROR: test_return_client_ordered_by_inscription_date (console.tests.TestBrowseClientsView) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/src/jengu/console/tests.py", line 164, in test_return_client_ordered_by_inscription_date context = view.get_context_data() File "/usr/src/jengu/console/views.py", line 34, in get_context_data owner=self.request.user.id).order_by(self.kwargs["order"]) KeyError: 'order' ---------------------------------------------------------------------- Why is that the case? I managed to fix my problem by passing status and order explicitly but it looks a bit ad hoc: def get_context_data(self, status, order, **kwargs): def test_return_clients_ordered_by_parameter(self): view = BrowseClients() view.setup(self.request) context = view.get_context_data("all", "inscription") Among the different options mentioned here, which one is the more canonical? Am I taking a wrong path, explicitly using variables when defining get_context_data()? -
Django/ i have modal where i can change password users
I have problem when i change password user. How can i add hash password or just password edit? thanks for answers -
Django Formtools Add Formset Dynamically
I am using Django Formtools to create a multistep form for a Job posting process. In one of the forms, I have Job Questions which I want the user to add dynamically, say a checkbox that generates the question form if they are interested in adding questions. They should have a button to create as many questions as possible. Now my challenge is that when I use normal model forms, I am able to complete the job posting process but if i replace the question form with a model formset and include it in the form_list I get key errors. Secondly, if I try the various Javascript responses on adding fields dynamically such as this stack overflow response, I get form validation errors. Just to mention, the question Form uses the same model as the other forms (Job Model) thus my expectation is that regardless of how many questions are added they will be save to the Job Model. Does anyone know how to go about this? Adding fields in Django formtools dynamically and saving to the model? My Form tools wizard looks as below: class JobWizard(SessionWizardView): form_list=[JobForm7,JobForm1,JobForm2,JobForm3, JobForm4,JobForm5,JobForm6 ] file_storage= FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'jobs')) template_name="jobs/jobforms.html" def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, … -
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', ...]