Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Previously Working Model Query Now Returns Nothing
In my Django project, an instance of a model is created in the first view. Then, in the second view, it is accessed and a couple of previously empty fields are updated. In the third view, I am attempting to run a docusign API using the information that is contained in the model instance. However, when I query for it the same way as I have in the second view, it returns 'None'. def firstView(request): if request.method=='POST' or request.method=='FILES': form = myObjForm(request.POST, request.FILES) newObj = myObj( phonenumber = request.POST.get('phonenumber')#There are several other fields that are occupied, but I pass the "phonenumber" between views to be able to retrieve the same instance between views ) newObj.save() return HttpResponseRedirect('pdf/{}'.format(newObj.phonenumber)) #Some other code def secondView(request, phone_number): myobj = myObj.objects.filter(phonenumber=phone_number).order_by('id').last() #pull the most recent instance. This does work. myObj.pdf = 'path/to/pdf.pdf' myObj.save() return HttpResponseRedirect('sign/{}'.format(phone_number)) def ThirdView(request, phone_number): myobj = myObj.objects.filter(phonenumber=phone_number).order_by('id').last() #This is where I get a 'None' type response. #Do some things with the model return HttpResponseRedirect('../success/') def success(request): return render(request, 'myapp/success.html') I would expect the query in ThirdView to return the same result it did in secondView. However, instead of returning the correct instance of the model, it returns 'None'. If I visit … -
Django, using sqlite for static content and postgresql for everything else
I would like to get some comments on whether this is a totally crazy idea or not. I have a django project running postgresql as its main database. This project has reports that have a lot of dynamic text content depending on values when the report is generated. I also have things like blog posts which are stored in this database. Currently, it's quite annoying when moving things from my dev envionment to production because it means I need to replicate what I have done in the dev database into the production database. I was wondering if I could use sqlite for this kind of static content only, like text, so things that are read only. I could then have this sqlite db under version control and use automatically transfer changes to production this way? So I would have postgresql as my main db and then sqlite as kind of a static only db for particular content. Thoughts? -
inject param to raw query python
When using (where user_id=1) I can get the result but when inject param I got traceback like this: 'User' object is not iterable, any ideas for inject param to raw query, my views.py: class TransactionViews(viewsets.ViewSet): def list(self, request): user = get_object_or_404(User, pk=request.user.id) queryset = Transaction.objects.raw("SELECT product.name, transaction.* from product inner join variant on product.id = variant.product_id inner join transactions_variants on variant.id = transactions_variants.variant_id inner join transaction on transactions_variants.transaction_id = transaction.id where user_id=%s",user) serializer = TransactionSerializer(queryset, many=True) return Response(serializer.data, status=200) one more question: queryset = Transaction.objects.filter(user_id=user).exclude(deleted_at__isnull=False) how can i convert this ".exclude(deleted_at__isnull=False)" into my raw query (this exclude is condition for soft delete) Traceback: File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/rest_framework/viewsets.py" in view 116. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py" in dispatch 495. response = self.handle_exception(exc) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception 455. self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py" in dispatch 492. response = handler(request, *args, **kwargs) File "/code/yashoes/transaction/views.py" in list 29. return Response(serializer.data, status=200) File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py" in data 765. ret = super(ListSerializer, self).data File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py" in data 262. self._data = self.to_representation(self.instance) File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py" in to_representation … -
Django update_or_create is too slow with ORM
I have a table named MyTable, that is saving IoT data id and time is unique together id | time | field1 | field2 | field3 django code: kwargs['id'] = 1 kwargs['time'] = '2018-01-01 00:00:00' update_kwargs[field1] = 12.34 instance, created = MyTable.objects.update_or_create(**kwargs, defaults=update_kwargs) My data soruce like streaming, field1 or field2 and field3 will one by one streaming in. but now, I got a large number flow have to update or create, almost every second have data streaming, that number is about 1,000,000 hr/row, the upsert not so fast I thought, how can I improve that? by the way, I use postgresql.