Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My django blog isnt detecting the HTML/CSS files i added
Edit 1: I am building a blog with django and i recently added some html/css files to a template folder but its not loading. These are my html codes base.html: {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/blog.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> <div id="sidebar"> <h2>My blog</h2> <p>This is my blog.</p> </div> </body> </html> list.html > {% extends "blog/base.html" %} {% block title %}My Blog{% endblock > %} {% block content %} <h1>My Blog</h1> {% for post in posts %} > <h2> > <a href="{{ post.get_absolute_url }}"> > {{ post.title }} > </a> > </h2> > <p class="date"> > Published {{ post.publish }} by {{ post.author }} > </p> > {{ post.body|truncatewords:30|linebreaks }} {% endfor %} {% endblock %} i could be wrong but i think the issue might be from the views and urls below views.py > from django.shortcuts import render, get_object_or_404 from .models > import Post > > def post_list(request): posts = Post.published.all() return > render(request, > 'blog/post/list.html', > {'posts': posts}) > > def post_detail(request, year, month, day, post): post = > get_object_or_404(Post, slug=post, > status='published', > publish__year=year, > … -
Django import-export name 'name' is not defined
hello guys i need import excel file in django admin i found this this video and I applied the steps but i have Line number: 1 - name 'name' is not defined error how can i solved models.py from django.db import models class Ekle(models.Model): name = models.CharField(max_length = 50, blank = False) lastname = models.CharField(max_length = 50) price = models.CharField(max_length = 50) def __str__(self): return name admin.py from django.contrib import admin from .models import * from import_export.admin import ImportExportModelAdmin @admin.register(Ekle) class ViewAdmin(ImportExportModelAdmin): pass -
How to send a JSON request from JAVASCRIPT to PYTHON script in Django?
I'm writing a django application, and I want to pass JSON data from a python file to a JAVASCRIPT file included in a view. All are on the same server. I tried to simply request the .py script via javascript using AJAX over the same server. The current code" ==)JAVASCRIPT: $.ajax({ type: 'GET', url: 'location_json.py', data: returned_from_json, dataType: 'jsonp', success: function(returned_from_json) { alert(returned_from_json); }, error: function() { alert('Error loading '); } }); ==)PYTHON: #!/bin/python3 import json import urllib.request print(---------------python----------------) #JSON PARAMETERS url = "http://127.0.0.1/my/url" #url to my server body = {'lat':12112,'lng': 5333324} request = urllib.request.Request(url) request.add_header('Content-Type','application/json; charset=utf-8') jsonData = json.dumps(body) jsonDataBytes = jsonData.encode('utf-8') request.add_header('Content-Length',len(jsonDataBytes)) print("json data:"+jsonDataBytes) response = urllib.request.urlopen(request, jsonDataBytes) if(!response) { response = urllib.request.urlopen(request, jsonDataBytes) } print("json sent") Output should be the content of : body = {'lat':12112,'lng': 5333324} lat and lng here have arbitrary for test reasons values. -
How Can I be make django orm with raw sql query?
I am working on a project and also new in django. I have the sql raw query having some joins in it. But my requirement is to make the django orm. I have tried to make it but not able to make the exact orm for that query. I have tried this to make the django orm but dont find exact result: model_data = Model.objects.prefetch_related( 'modelapi', 'modelauth', 'modelapiconfig').filter( modelauth__retrieval_id='XXYY',modelauth__is_active=True).values( 'model_name', 'modelauth__retrieval_id', 'modelapi__api_endpoint_name', 'modelapi__modelapiconfig__api_config') Here is my models.py: class Model(models.Model): model_name = models.CharField(max_length=40, blank=False, verbose_name='Name', unique=True) def __str__(self): return self.model_name class Meta: db_table = 'connector_model' class ModelApi(models.Model): model_id = models.ForeignKey(Model, on_delete=models.CASCADE, verbose_name='MODEL Name', related_name='modelapi') model_description = models.CharField(max_length=150, verbose_name='API Description') api_endpoint_name = models.CharField(max_length=100, blank=False, verbose_name='API endpoint name', default='') def __str__(self): return self.model_id.model_name + "_" + self.api_endpoint_name class Meta: db_table = "connector_model_api" class ModelAuthentication(models.Model): model_id = models.ForeignKey(Model, on_delete=models.CASCADE, verbose_name='MODEL Name', related_name='modelauth') email = models.EmailField(max_length=70) retrieval_id = models.CharField(max_length=30, blank=False, unique=True) def __str__(self): return self.model_id.model_name + "_" + self.retrieval_id class Meta: db_table = "connector_model_authentication" class ModelApiConfig(models.Model): model_auth = models.ForeignKey(ModelAuthentication, on_delete=models.CASCADE, verbose_name='MODEL Customer Name') model_api = models.ForeignKey(ModelApi, on_delete=models.CASCADE, verbose_name='MODEL API', related_name='modelapiconfig') api_config = models.TextField(default={}) def __str__(self): return self.model_auth.model_id.model_name + str("'s ") \ + self.model_api.api_endpoint_name + str(" endpoint") class Meta: unique_together = ('model_auth', 'model_api',) db_table = "connector_model_api_config" … -
Dictionaries inside Lists - Django
I am using session in my Django Application. request.session['permissions'] is having a data like bellow. The key is same for every values. Basically it is dictionaries inside list [{'mykey': 'value1'}, {'mykey': 'value2'}, {'mykey': 'value3'}, {'mykey': 'value4'}, {'mykey': 'value5'}, {'mykey': 'value6'}] permissions = request.session['permissions'] Now i want to check if value4 is present inside permissions. I am not getting how to check the value. Whenever i am trying to access value like this permissions.mykey It is giving me error 'list' object has no attribute 'mykey' I want to do similar like this permissions = request.session['permissions'] if value not in permissions: print('Value is inside list') -
ListView in Django Assistance
OK, so I have just done a rather extensive Django tutorial online and wanted to dive into my first project to see how I would go. I started off alright and then hit a pretty big road block that I am trying to overcome with no luck, so if you guys could help I will be forever in your debt! So the project itself is simply making a website for a few of my mates where we can login and view some stats on bets we have with each other. What I have done so far: I created two models in models.py with the following code: from django.db import models # Create your models here. class Team(models.Model): team_name = models.CharField(max_length=500, unique=True) wins = models.PositiveIntegerField() losses = models.PositiveIntegerField() class Predictions(models.Model): combined_teams = models.CharField(max_length=800) player_name = models.CharField(max_length=200, primary_key=True) predicted_wins = models.PositiveIntegerField() def __str__ (self): return self.player_name I created a login screen, this is the first screen the user will come to (not relevant for the question) I created a static folder with some css styling for a couple of the pages and made some minor changes to the settings files. I then went on to setup my views.py file and a couple … -
How to add html id to django's built in log in form
I am working on a django application. I added a login page to the application. In the login page I want to add a show password checkbox which when checked shows the password. I have written some javascript code for that purpose. this is the code to show passowrd js code to show passowrd function myFunction() { var x = document.getElementById("myInput"); if (x.type === "password") { x.type = "text"; } else { x.type = "password"; } } Now my problem is this code only works if the password field has the id myinput. How do I add this to django's built in login form? -
Django Rest Framwork CSRF cookie not found for PUT method
I'm getting started with DRF, I created a class based view for some CRUD operations, so the GET and POST method work fine, however when I try to send a PUT request from Postman, I get the following error : Forbidden (CSRF cookie not set.): /post/1 I read that as_view() call csrf_exempt internally so it should have exempted the csrf token issue, I also tried with method decorators, however it did not worked as well. urls.py ... url(r'^post$',PostView.as_view()), #url(r'^post/(?P<pk>\d+)/$',PostView.as_view()), ... Can someone let me know, where I'm going wrong? -
how to call model methods in template
how to call the model method get_url() in the template i want to call the model method get_url() in the tag in the template models.py class Department(Base): department_name = models.CharField(max_length=128) description = models.TextField(null=True, blank=True) def get_url(self): ct = ContentType.objects.get(model='department') url_name = ' %s:%s ' % (ct.app_label, ct.model) return reverse(url_name, args=(self.object_id)) template.html <a href="{% ? ... how to call the model method here.... ? %}"></a> -
How to unzip a zip file and show it as list in python-Django
I'am learning python and django, I want to make an endpoint that takes zip file and iterate through it and shows me the item list inside the zip file. What would be the easiest way to implement this? I have tried something, as my knowledge in django is not good at all. from django.core.files.storage import FileSystemStorage import zipfile class Upload(View): def post(self, request): context = {} if request.method == 'POST': uploaded_file = request.FILES['filename'] zf = zipfile.ZipFile(uploaded_file) print zf.namelist() for filename in zf.namelist(): fs = FileSystemStorage() rename = 'uploadedFile.jpg' name = fs.save(rename, filename) context['url'] = fs.url(name) return render(request, 'app.html', context) so basically my purpose is to take a zipfile from and rename it and makke an url for each. My stated code is not the right way to do this as its bringing some error, would you please help me with the right way? -
How to make posts similar to facebook in django? [duplicate]
This question already has an answer here: Django for social networking 7 answers Want to make an social networking site with django but can't get idea to make posts in django. plz help me. thanks! -
how to solve this error with django and ajax?
i just want to pass the selected id of the option via ajax request to django 2.1 but it always returns me some errors . i am new to django and web development so please help to solve this issue -
Django PSYCOPG2 db connection
I have created a django api with the following views.py import datetime import os import traceback from logging.handlers import TimedRotatingFileHandler from logging import Formatter from django.http import HttpResponse import logging # from . import models as m import pandas as pd import json import psycopg2 as pg # logger setup filename = datetime.datetime.now().strftime('%Y-%m-%d') + '.log' if not os.path.exists('./Logs'): os.mkdir('./Logs') handler = TimedRotatingFileHandler('Logs/' + filename, when='midnight', backupCount=8) formatter = Formatter(fmt='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%d-%m-%Y %I:%M:%S %p') logger = logging.getLogger('werkzeug') handler.setLevel(logging.INFO) handler.setFormatter(formatter) logger.setLevel(logging.INFO) logger.addHandler(handler) logger.propagate = False def resp(status): //returns status code def index(request): logger.info('request:' + str(request.GET)) obj = DAA() if request.method == "GET": // get values from url request if (condition): try: connection = pg.connect(dbname="dbname", user="user", password="password") cursor = connection.cursor() logger.info('connection successful') response = obj.level1(arguments) response = obj.level2(arguments) try: // check response except Exception as e: # m.connection.close() # added logger.error(msg='Exception occured No Count\t' + str(e) + '\tTraceback\t' + '~'.join(str(traceback.format_exc()).split('\n'))) except Exception as e: logger.error(msg='Exception occured\t' + str(e) + '\tTraceback\t' + '~'.join(str(traceback.format_exc()).split('\n'))) # connection.close() if response : json_data = { "responseCode": 200, "version": "1.0.0", "results": [ // response ] } json_dump = json.dumps(json_data) logger.info('responseCode:200') # m.connection.close() # added return HttpResponse(json_dump, content_type='application/json') elif not response : json_dump = resp(400) logger.info('responseCode:'+json_dump) return HttpResponse(json_dump, … -
Pass certain values or parameters on response - django
So I have this code which is which is adding field to the response object, and I would like to access the variable on the front end. import time import logging log = logging.getLogger(__name__) class ResponseTimeInstrumentation(object): def process_request(self, request): request.instrumentation_start_time = time.time() def process_response(self, request, response): duration = time.time()-request.instrumentation_start_time response["page_loading_duration"] = duration return response I know the response.content is already rendered but I want this field somehow to be accessible on the front end -
Fix render() got an unexpected keyword argument 'renderer' in Django 2.1
I'm resurrecting some old code that use to work in Django 1.9. I'm trying to convert this code over to Django 2.1, but this one package that is part of my project has some compatibility issues. I'm looking to correct the render() type error. @login_required def compose(request, recipient=None, form_class=ComposeForm, template_name='django_messages/compose.html', success_url=None, recipient_filter=None): """ Displays and handles the ``form_class`` form to compose new messages. Required Arguments: None Optional Arguments: ``recipient``: username of a `django.contrib.auth` User, who should receive the message, optionally multiple usernames could be separated by a '+' ``form_class``: the form-class to use ``template_name``: the template to use ``success_url``: where to redirect after successfull submission """ if request.method == "POST": sender = request.user form = form_class(request.POST, recipient_filter=recipient_filter) if form.is_valid(): form.save(sender=request.user) messages.info(request, _(u"Message successfully sent.")) if success_url is None: success_url = reverse('messages_inbox') if 'next' in request.GET: success_url = request.GET['next'] return HttpResponseRedirect(success_url) else: form = form_class() if recipient is not None: recipients = [u for u in User.objects.filter( **{'%s__in' % get_username_field(): [r.strip() for r in recipient.split('+')]})] form.fields['recipient'].initial = recipients return render(request, template_name, { 'form': form, }) And here is the traceback: File "/Users/justinboucher/PycharmProjects/awaylm/django_messages/views.py", line 96, in compose 'form': form, File "/anaconda3/envs/awaylm/lib/python3.6/site-packages/django/forms/boundfield.py", line 33, in __str__ return self.as_widget() File "/anaconda3/envs/awaylm/lib/python3.6/site-packages/django/forms/boundfield.py", line 93, in … -
Format date of a Django variable in JQuery
I've got a date in the short format such as Jan. 24 2019 as a Django variable. How can I format this as 24/01/2019? -
How can i implement app namespace in django commands?
I want to implement django app namespacing in commands like python manage.py appname:command --parameters and python manage.py appname:command:subcommand --parameters how I can do this ? -
Django/DataTables - Template Loop breaks DataTable
When placing a template loop in my table-row my DataTable breaks. <table id="store_table" class="table-striped table-hover"> <thead class="thead-light"> <tr> <th>Store #</th> <th>Name</th> <th>Phone</th> <th>City</th> <th>State</th> </tr> </thead> <tbody> {% for store in stores %} <tr id="table-row"> <td><a href="/stores/{{ store.pk }}">{{ store.store_number }}</a></td> <td><a href="/stores/{{ store.pk }}">{{ store.name }}</a></td> <td>{{ store.phone }}</td> <td>{{ store.city }}</td> <td>{{ store.state }}</td> {% for circuit in store.circuit_set.all %} <td>{{ circuit.circuit_id }}</td> {% endfor %} <td>{{ store.postal }}</td> </tr> {% endfor %} </tbody> </table> Console Output: jQuery.Deferred exception: i is undefined Ha@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:24:397 O@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:16:421 na/<@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:17:21 map/<@https://code.jquery.com/jquery-3.3.1.min.js:2:1324 map@https://code.jquery.com/jquery-3.3.1.min.js:2:3169 map@https://code.jquery.com/jquery-3.3.1.min.js:2:1292 na@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:16:497 e@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:92:431 n/<@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:93:118 each@https://code.jquery.com/jquery-3.3.1.min.js:2:2571 each@https://code.jquery.com/jquery-3.3.1.min.js:2:1238 n@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:83:194 h.fn.DataTable@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:165:488 @http://10.200.20.63:8080/stores/:12810:19 l@https://code.jquery.com/jquery-3.3.1.min.js:2:29373 a/</c<@https://code.jquery.com/jquery-3.3.1.min.js:2:29677 undefined So I'm assuming this is because {% %} isn't a recognized/handleable table element. -
Many to many objects duplicated
I am running a process to migrate a lot of call data. I have a model representing a phone line, and another model representing a caller. A phone line can have more than one caller, and a caller can phone more than one phone line. So a many to many relation is needed. For 442/444 of the phone lines, the code below works and the caller is created and linked to a phone line or added to the relation. However, in 2 cases duplicates are being created. That is, the phone line will store two caller instances with the same number. How can I prevent this? try: caller = Caller.objects.get(number=number) except ObjectDoesNotExist: caller = Caller.objects.create(number=number) caller.save() if not caller.phoneline.filter(pk=phoneline.pk).exists(): caller.phoneline.add(phoneline) -
django heroku whitenoise issute( static files loading related)
By heroku logs --tail, I got these errors: ImportError: Your WhiteNoise configuration is incompatible with WhiteNoise v4.0 and django.core.exceptions.ImproperlyConfigured: WSGI application 'myproject.wsgi.application' could not be loaded; Error importing module. in my wsgi.py(I intentionly removed whitenoise-related lines): import os from django.core.wsgi import get_wsgi_application from dj_static import Cling os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'notetaking.settings') application = Cling(get_wsgi_application()) in Procfile: worker: gunicorn --pythonpath notetaking notetaking.wsgi in prod_settings.py from .settings import * STATIC_ROOT='staticfiles' SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO','https') ALLOWED_HOSTS = ['*'] DEBUG = False import dj_database_url DATABASES = { 'default': dj_database_url.config() } STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' in requirements.py dj-database-url==0.5.0 dj-static==0.0.6 Django==2.1.5 djangorestframework==3.9.1 gunicorn==19.9.0 mysqlclient==1.3.13 numpy==1.16.0 pandas==0.23.4 Pillow==5.4.1 psycopg2==2.7.7 python-dateutil==2.7.5 pytz==2018.9 six==1.12.0 static3==0.7.0 virtualenv==16.2.0 whitenoise==4.0 xlrd==1.2.0 -
How to Setup Generic Relations to Query Multiple Models in Django
I'm working with a legacy postgres 10 database that has about 50+ models and I'm building a search to query fields in the following models: class Eligibilities(models.Model): id = models.IntegerField(primary_key=True) nct = models.ForeignKey(Studies, on_delete = models.CASCADE, db_column = 'nct_id') #nct = models.CharField(max_length = 100, unique=True, db_column = 'nct_id') #nct = GenericRelation(Studies) gender = models.CharField(max_length = 10000, blank=True, null=True) criteria = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'eligibilities' class Conditions(models.Model): id = models.IntegerField(primary_key=True) nct = models.ForeignKey(Studies, on_delete = models.CASCADE, db_column = 'nct_id') #nct = models.CharField(max_length = 100, unique=True, db_column = 'nct_id') #nct = GenericRelation(Studies) ConditionsName = models.CharField(max_length = 10000, blank=True, null=True, db_column = 'name') class Meta: managed = False db_table = 'conditions' I'd like to query the gender and criteria fields in the Eligibilities model and the ConditionsName field in the Conditions model. Based on the query I'd like to see field data from the related models below: class Studies(models.Model): #id = models.IntegerField(primary_key=True) nct = models.CharField(primary_key=True, max_length = 100, unique=True, db_column = 'nct_id') #content_type = models.ForeignKey(ContentType, on_delete = models.CASCADE) #nct = models.CharField(primary_key=True, max_length = 100, unique=True, db_column = 'nct_id') #content_object = GenericForeignKey('content_type', 'nct') brief_title = models.TextField(blank=True, null=True) official_title = models.TextField(blank=True, null=True) class Meta: managed = False db_table = … -
Django: how to filter objects by last 6 bits of binary field?
I have a field for storing object's metadata in compact way. class Foo(models.Model) meta = models.BinaryField( max_length = 8, editable = True, default = 0b11000000 ) ... How can I sort my objects using only last 6 bits of meta like this: query_set = Foo.objects.filter(meta = 0b~any two bits~000000 | 0b111111) It's very crucial for me to store metadata this way. -
Django - Fetch all related in template loop
I have a data table that creates a row for every Store object. I am using Django 2.1 <tbody> {% for store in stores %} <tr id="table-row"> <td><a href="/stores/{{ store.pk }}">{{ store.store_number }}</a></td> <td><a href="/stores/{{ store.pk }}">{{ store.name }}</a></td> <td>{{ store.phone }}</td> <td>{{ store.city }}</td> <td>{{ store.state }}</td> {% for circuit in circuits %} <td>{{ circuit }}</td> {% endfor %} <td>{{ store.postal }}</td> </tr> {% endfor %} </tbody> What I'm wanting to do is create a table column for every circuit where store is the given store number. Models: class Store(models.Model): store_number = models.IntegerField(default=0000, unique=True) name = models.CharField(max_length=100) phone = models.CharField(max_length=15) xo_tn = models.CharField(max_length=15, null=True) street_address = models.CharField(max_length=50, null=True) city = models.CharField(max_length=50, null=True) state = models.CharField(max_length=50, null=True) postal = models.CharField(max_length=15, null=True) timezone = models.CharField(max_length=40, null=True) date_opened = models.DateField(blank=True, null=True) date_closed = models.DateField(blank=True, null=True) def __str__(self): string = '{0} - {1}'.format(self.store_number, self.name) return string def number(self): return self.store_number class Circuit(models.Model): circuit_id = models.CharField(max_length=100) store = models.ForeignKey(Store, null=True, on_delete=models.SET_NULL) provider = models.ForeignKey(Provider, blank=True, null=True, on_delete=models.SET_NULL) configuration = models.ForeignKey(CircuitConfiguration, null=True, on_delete=models.SET_NULL) registered_on = models.DateTimeField(auto_now=True) delivered_on = models.DateField(auto_now=True) is_active = models.BooleanField(default=True) def __str__(self): return self.circuit_id View: @login_required def stores(request): stores = Store.objects.exclude(street_address__contains="closed").all() context = { 'stores':stores, } return render(request, 'all_stores.html', context) I have not … -
Django Regex URL pattern overriding other URLs
I am working on a project which requires to display the data about a city which is requested through the url like example.com/city1 for city1 information etc. I have used the below url pattern & view in my app. This view is working fine. url(r'^(?P<cityId>[-\w]+)$',views.cityindex,name='cityindex'), def cityindex(request, cityId): city = City.objects.filter(url = cityId) if len(city) == 0: return redirect('/404') return HttpResponse('City Data Extracted') But when I try to open other urls like /admin or urls from other app it is being redirected to my cityindex view and then to 404 page as handled in my view above. Below is the url patterns I used in my main urls.py file. url(r'^', include('main.urls')), url(r'^admin/', admin.site.urls), url(r'^login_redirect/', include('loginapp.urls')), I am presently using Django 1.11.12. Is there any way to stop this url from overriding? -
Django + Gunicorn + SCRIPT_NAME
I have a number of django apps running off the same domain but am having problems getting SCRIPT_NAME to work properly with Gunicorn. Example app paths: www.domain.com/app1 www.domain.com/demo Scenario1: I currently have each app running on Elastic Beanstalk and modify the apache config to deal with the SCRIPT_NAME side of things. This works. Scenario2: I have been testing using AWS ECS/FARGATE and in that config I only have a container running Django/Gunicorn. There is no Apache/Nginx etc. I intend to just use Django/Gunicorn/Whitenoise/Cloudfront. This is not working. The SCRIPT_NAME value to make django work with sub paths is duplicating. To simplify/troubleshoot I am running the code/commands below locally, so AWS is not involved. I have also created a bare bones/simple django app for testing. My app page structure is like this: Home Page1 Link <a href="{% url 'demo:page1' %}">Page1</a> Home Link <a href="{% url 'demo:home' %}">Home</a> Page2 Link <a href="{% url 'demo:page2' %}">Page2</a> Home Link <a href="{% url 'demo:home' %}">Home</a> Steps: I launch the webserver: gunicorn config.wsgi --env SCRIPT_NAME=demo -b 0.0.0.0:80 --keep-alive 20 --log-file=- --log-level debug --capture-output (its running in a docker container) I can go to http://127.0.0.0:8000/demo. It loads the app home page as expected. The Page1 link shows …