Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django- url not displaying page despite changing
This is the index.html {% extends 'base.html' %} {% block content %} <h1>list of {{title}}</h1> {% if questions %} <ul> {% for question in questions %} <li> <a href="/polls/{{question.id}}/details/"> {{question.title}}</a> </li> {% endfor %} </ul> {% else %} <p>there is a no question available</p> {% endif %} {% endblock %} details.html {% extends 'base.html' %} {% block content %} <H2>Details Page</H2> <h3>{{question.title}}</h3> {% for choice in question.choices %} <p>{{choice.text}}({{choice.votes}})</p> {% empty %} <p>There is no choice available for this Question</p> {% endfor %} <p>Poll is created by {{question.created_by.first_name}}</p> {% endblock %} This is base.html {%load static%} <html lang="en"> <head> <meta charset="UTF-8"> <title>WebPage</title> <link rel="stylesheet" href="(%static 'css/custom.css'%)"> </head> <body> <h1>Welcome to My Page</h1> {% block content %} {% endblock %} </body> </html> And poll.urls from django.conf.urls import url from poll.views import * urlpatterns = [ url('', index, name='polls_list'), url('<int:id>/details/', details, name='polls_details') ] So this is what happens I have 3 questions that display on the index.html, on clicking any of them it changes to the proper url but does not open the requested page. How do I solve this. Do keep in mind that i just started django two days ago so pardon my naivety.Thanks -
How get value from aggregations in Elasticsearch dsl
I began to understand with Elasticsearch dsl and faced with problem. I can not get value from aggregations. I is use the metric method, but is get a error, when I want to get the value from 'new_distance'. What doing wrong? res = MyIndex.search()\ .filter('geo_distance', distance='1km', location={"lat":"32.895", "lon":"21.115"})\ .aggs.metric('new_distance', 'max', field='point') result = res.to_queryset() print(result[0].new_distance) error 'Comments' object has no attribute 'new_distance' -
Multiple image upload in Django using AJAX & jQuery
I want to implement dynamic multiple image upload for an application in Django. I got to know that Django doesn't have any in-built support for that and external libraries have to be used. I followed the blog - https://simpleisbetterthancomplex.com/tutorial/2016/11/22/django-multiple-file-upload-using-ajax.html But the result I'm getting is nowhere close to what is expected. Starting with settings.py import os SETTINGS_DIR = os.path.dirname(__file__) PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir) PROJECT_PATH = os.path.abspath(PROJECT_PATH) MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media') MEDIA_URL = '/media/' models.py class Images(models.Model): file = models.FileField(upload_to='profile_images') category = models.CharField(max_length=20, blank=False) time = models.DateTimeField(auto_now_add=True) def __unicode__(self): return self.category forms.py class ImagesForm(forms.ModelForm): class Meta: model = Images fields = ['file',] upload.html <!DOCTYPE html> <html> <head> <title>Upload</title> </head> <body> <form id="category_form" method="post" action="/rango/upload/" enctype="multipart/form-data"> {% csrf_token %} <script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.22.0/js/vendor/jquery.ui.widget.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.22.0/js/jquery.iframe-transport.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.22.0/js/jquery.fileupload.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.22.0/js/jquery.fileupload.js"></script> {# 1. BUTTON TO TRIGGER THE ACTION #} <button type="button" class="btn btn-primary js-upload-photos"> <span class="glyphicon glyphicon-cloud-upload"></span> Upload photos </button> {# 2. FILE INPUT TO BE USED BY THE PLUG-IN #} <input id="fileupload" type="file" name="file" multiple style="display: none;" data-url="{% url 'upload' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> {# 3. TABLE TO DISPLAY THE UPLOADED PHOTOS #} <table id="gallery" class="table table-bordered"> <thead> <tr> <th>Photo</th> </tr> </thead> <tbody> {% for photo in photos %} <tr> <td><a href="{{ photo.file.url }}">{{ … -
Change "activate_url" in email confirmation in django allauth
The email is being sent from the template email_confirmation_message.txt {% load account %}{% user_display user as user_display %}{% load i18n %}{% autoescape off %}{% blocktrans with site_name=current_site.name site_domain=current_site.domain %}Hello from {{ site_name }}! You're receiving this e-mail because user {{ user_display }} has given yours as an e-mail address to connect their account. To confirm this is correct, go to {{ activate_url }} {% endblocktrans %}{% endautoescape %} {% blocktrans with site_name=current_site.name site_domain=current_site.domain %}Thank you from {{ site_name }}! {{ site_domain }}{% endblocktrans %} The activate_url is sending link as http://web/en/accounts/confirm-email/Mjc:1fWFRw:q-ScRb0Wnsrrem9N7pB9iLOuPOM/ where web is my conatiner hostname. How can I change this to custom domain name without having to change my conatiner hostname. I am using django-allauth==0.33.0 -
Django: How to get a distinct Parent List from a Child Queryset related to the User?
These are my models where Apps have menu_items: class App(models.Model): name = models.CharField(max_length=50) class Menu(models.Model): name = models.CharField(max_length=120) app = models.ForeignKey(App, on_delete=models.PROTECT) url = models.CharField(max_length=120, null=True) class Meta: ordering = ['name', 'app'] This is my View, is there any way this can be optimized? class AboutView(TemplateView): template_name = 'about.html' def get_context_data(self, *args, **kwargs): context = super(AboutView, self).get_context_data(*args, **kwargs) menu_items = Access.objects.filter(user__id=self.request.user.id) applist = [] for m in menu_items: applist.append(m.menu.app.name) apps = App.objects.filter(name__in=applist) context = { "menu_items": menu_items, "apps": apps } return context -
Can Hubot Slack bot store sessions
I am trying to implement simple slack bot. So I have configured hubot which will take inputs from slack and passing it to my webapp (django app) and it will take whatever the response from django-app and will reply to slack. In this process I am trying to store session in django using request.session but that is not reflected in slack. If I am accessing the django-url in browser it is able to store sessions and getting proper response with session. So it is the problem with slack or my approach and is there a way to store sessions in hubot when requesting to django-app -
KeyError: how to correctly set a variable in form_invalid()
As an introduction, I know that I'm doing something wrong in the line: search_text = form.cleaned_data['search_text'] in views.py, but I can't figure out how to correctly set that variable in form_invalid() PROBLEM If a User entered a search_text in the Form that already existed in the database, an Error would be caused: "Hashtag with this Search text already exists." SOLUTION If a User enters a search_text that already exists in the database, check whether the search_text entered matches an existing search_text in the database. If so, render results.html. ERROR Request Method: POST Request URL: http://ozxlitwi.apps.lair.io/search_query/ Django Version: 2.0 Exception Type: KeyError Exception Value: 'search_text' Exception Location: /mnt/project/mapping_twitter/views.py in form_invalid, line 31 Python Executable: /mnt/data/.python-3.6/bin/python Python Version: 3.6.5 Python Path: ['/mnt/project', '/mnt/data/.python-3.6/lib/python36.zip', '/mnt/data/.python-3.6/lib/python3.6', '/mnt/data/.python-3.6/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6', '/mnt/data/.python-3.6/lib/python3.6/site-packages'] CODE models.py import re from django.db import models from twython import Twython class Location(models.Model): """ Model representing a Location (which is attached to Hashtag objects through a M2M relationship) """ name = models.CharField(max_length=1400) def __str__(self): return self.name class Hashtag(models.Model): """ Model representing a specific Hashtag serch by user """ search_text = models.CharField(max_length=140, primary_key=True) locations = models.ManyToManyField(Location, blank=True) def __str__(self): """ String for representing the Model object (search_text) """ return self.search_text def display_locations(self): """ Creates a … -
Django file upload:Integrity Error
This is what I got IntegrityError at /malex/upload/ NOT NULL constraint failed: malex_document.uploaded_by_id Request Method: POST Request URL: http://127.0.0.1:8000/malex/upload/ Django Version: 2.0.5 Exception Type: IntegrityError Models class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d') uploaded_by = models.ForeignKey(Profile,on_delete=models.CASCADE) date_uploaded = models.DateTimeField(auto_now_add=True) Forms class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) class DocumentForm(forms.Form): docfile = forms.FileField(label='Select a file') views def upload(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('upload')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return render(request,'upload.html',{'documents': documents, 'form': form}) Traceback Traceback: File "/home/milenko/miniconda3/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) File "/home/milenko/miniconda3/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute 303. return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: malex_document.uploaded_by_id) was the direct cause of the following exception: File "/home/milenko/miniconda3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/milenko/miniconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/milenko/miniconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/milenko/nup/malex/views.py" in upload 38. newdoc.save() What even amkes things more strange with this integrity error is that the file … -
Django drf get List<String> from Android but this is string
django 2.0.2 python3.4 django view.py class Test(viewsets.ModelViewSet): queryset = '' serializer_class = BaseSerializer def create(self,request): print(request.data.dict()) return Response(0) androidSend @Field("Tests") List<String> Tests Log in Android return [1,2,3] but django print(request.data.dict()) return {"Tests":"3"} not List just Str how to get List from Android to django -
Easy way to set conditional uniqueness to django model
In the model below, while ham is same value, each spam need to be uniqu. class MyModel(models.model): ham = models.CharField(max_length=200) spam = models.CarField(max_length=200) I understand it's probably possible to validate them on form but just wonder if there is an easy way to do it on model. -
Security checks in django
We started migrating a java project to Django .Our present code we are using different filters for security. Mainly we are checking below filters · Session hijacking check · XSS attach check · CSRF check · Path manipulation check(directory traversal attack) · Access controller check When I go through Django security documents ,I come across CSRF ,Session and XSS security. I would like to know remaining security checks are already implemented in Django or we need to add our own check condition. We are not using Django templates for GUI .If we are adding angularJS for GUI, do we need to handle XSS security separately . -
Django: How can I render my page and at the end output the generated csv file?
I need assistance in how to allow this code to render the blank page , then render the page with returned values then also output the response(csv file) I have searched for hours and looked everywhere. Its kinda upsetting how I cant have two views for my page or add the response to the render.Thank you for your help def form_valid(request): account_result = {} if 'account_id' in request.GET: form = AccountForm(request.GET) if form.is_valid(): account_result,Size =form.form_valid() account_id=form.Account() subject=form.Subjects() response=form.Tabs() #return response return render (request,'test.html',{'form':form,'account_result':account_result,'Size':Size,'ID':account_id,'subject':subject} ) else: form = AccountForm() return render (request,'test.html',{'form':form,'account_result':account_result}) -
Using django-rules for attribute level access control?
In my django application, I have a model, Client, which holds information about the clients of my business. I have two groups of employees that uses my application - Technician and Finance. Members of Technician can view/update attributes of Client such as 'password_hash', 'login_ip_address'. Members of Finance can view/update attributes such as 'total_revenue' or 'bank_account_number'. I see in the documentation that Predicates can be created from any callable that accepts anything from zero to two positional arguments. Is it possible to extend this to three positional arguments? I am interested to do the following: @rules.predicate def can_view_attribute(user, model, attribute): If the above is not possible, I plan to generate a rule for the Client class for every of its attribute. Rule generation will happen at the initialization phase of my application. @rules.predicate def can_view_client_attribute(user, attribute): Are there any drawbacks to this approach? Has anyone attempted this approach before? -
Django set manual arithmetic formula for a field
I want to set manual arithmetic formula of a field in a model, the formula changes from object to object of the model and is set by some user. for example model A: field 1= int field 2 = int field 3 = set formula In object 1 of model A, User can set field3 = field1 + filed2 In object 2 of model A, User can set field3 = field1 * filed2 Is this possible in Django? -
difference between URL and path in Django?
I just started learning Django, and not able to understand that what is the actual difference between URL and path in Django. -
django 1.8 tutorial part 6
First off, I realize Django 1.8 is outdated but I'm required to learn it for a project. I got through the first five parts without any issues but when I try to link the stylesheet in part 6, my stylesheet isn't loading (there's no change in the page). I've gone over the code several times and checked the namespacing of each folder and it should be working but I can't seem to find the problem. If anyone has gone through this tutorial and could shed some light on the issue, I'd really appreciate it. Here's the code in mysite/polls/templates/polls/index.html: {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" /> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_t\ ext }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} And here's my stylesheet located at mysite/polls/static/polls/style.css: li a { color: green; } body { background: white url("images/background.gif") no-repeat right bottom; } -
Testing forms and widgets - Python
I trying to test the Django forms and widgets but it is returning false instead of true. The test looks right but not sure. class TestForm(TestCase): def test_player_interests_fail(self): form = PlayerInterestsForm(data={'interests': 'sport'}) self.assertEqual(form.is_valid(), True) class PlayerInterestsForm(forms.ModelForm): class Meta: model = Player fields = ('interests', ) widgets = {'interests': forms.CheckboxSelectMultiple} -
Dehydrate never called in Django-TastyPie Resource
I have the following resource that successfully POSTs data into my data base, but the dehydrate method never runs. Am I missing something? class BetsResource(ModelResource): success = fields.BooleanField() class Meta: queryset = Bets.objects.all() resource_name = 'bet' list_allowed_methods = ['get', 'post'] authorization = Authorization() filtering = { 'id': 'exact', 'user_id': 'exact', 'match_id': 'exact', 'currency': 'exact', 'when': ALL, 'amount': ALL, 'success': ALL } def dehydrate(self, bundle): # return False logger.info('First DEHYDRATE pass') return bundle -
Sharing via Whatapps and Wechat
currently i have django webapp and a qr code generated in html using: {% qr_from_text article.qr_code%}. The article article.qr_code is a uuid. However, now i would like to share the qr code image via whatapps/sms/wechat. Is there any way i can do it? Should i change my approach to: generate qrcode image and save in my models. How i save qr code image in model>? get qr code image url. How do i get qrcode image url from localhost database? share image url via whatapps and wechat?? -
How do I order a Queryset by model attributes in my template
What I want is to be able to sort baseball players by specific attributes via a drop down and display them as bootstrap cards in my template Views.py from django.shortcuts import render from stats.models import * def index(request): player_list = Player.objects.all() context_dict = {'player_list':player_list} return render(request, 'stats/index.html', context=context_dict) Models.py from django.db import models class Player(models.Model): picture = models.ImageField(blank=True) name = models.CharField(max_length=24) number = models.IntegerField(unique=True) jersey_name = models.CharField(max_length=20) games_played = models.IntegerField() at_bats = models.IntegerField(default=0) average = models.DecimalField(max_digits=4, decimal_places=3) hits = models.IntegerField() doubles = models.IntegerField() triples = models.IntegerField() home_runs = models.IntegerField() runs = models.IntegerField() rbis = models.IntegerField() def __str__(self): return self.name And here's what the I imagine the tag would look like in my template {% for player in player_list.filter_by_some_attribute %} HTML here {% endfor %} I looked for a solution here on SO and the Django docs but I'm fairly new to Django so phrasing my problem to find the solution is another challenge. I got the sense that custom template or filter tags might be what I'm looking for, but if I could get a push in the right direction that would be greatly appreciated. -
select2 large items performance
I'm using django and select2 plugin for my web service. It works very well with small items, But when the list is huge (more than 2500) it really slows down. What should I do? {{ form.select }} <!-- <select name="select" id="id_select"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> . . <option value="2500+">2500+</option> </select> --> <script> $('select[name=select]').select2(); </script> -
Save custom ManyToMany form on post django views
I'm biulding custom form with ManyToMany field MODELS.PY class Module(models.Model): class Meta(): db_table = "module" verbose_name = "Module" verbose_name_plural = "Modules" module_title = models.CharField( verbose_name="Module title", max_length=200, blank=False, null=False, ) module_menu_item = models.ManyToManyField( 'mega_admin.MenuItem', blank=True, null=True, ) VIEWS.PY module_menu_item = request.POST.getlist('menu_item_menu', '') save_module_form = ModuleForm(request.POST) if save_module_form.is_valid(): module = save_module_form.save(commit=False) module.module_title = module_title module.module_menu_item = module_menu_item save_module_form.save() This way I can successfuly add new module, however none module_menu_item are being created. on POST values are: module_menu_item_id {…} 0 28 1 22 2 27 3 25 So on one post, needs to be created more than one relation for module and menu item NOTE: I don't use default model based form in template -
Django filter by one and order by another value of ManyToMany relation
I have models: class A(models.Model): pass class B(models.model): a = models.ForeighKey(A) name = models.CharField() value = models.CharField() I need to get X (for example, X=10) items of A that are filtered by B.value if B.name == 'name1' and ordered by B.value if B.name == 'name2' using Django ORM only. The SQL of what I want is like: SELECT table_a.id FROM table_a INNER JOIN table_b ON (table_a.id = table_b.a_id) LEFT OUTER JOIN ( SELECT table_a.id as id, table_b.value as value FROM table_a INNER JOIN table_b ON (table_a.id = table_b.a_id) WHERE table_b.name = 'name2' GROUP BY table_a.id ) tmp_table ON (tmp_table.id = table_a.id) WHERE (table_b.name = 'name1' AND table_b.value::text LIKE '%mid%') GROUP BY table_a.id ORDER BY tmp_table.value LIMIT 10; For each item of A value of B.name is unique (that's why I used INNER JOIN). The easiest way I know is: # Filtering A a_set = dict((a.id, {'b': {}}) for a in A.objects.filter(b__name='name1', b__value__contains='mid')) # I just need to know all b-items for a_set # "a_id__in=<huge list>" is bad idea, so I want to paginate a_set before it for b in B.objects.filter(a_id__in=a_set): a_set[b.a_id]['b'][b.name] = b.value # Sorting where items of A without 'name2' will be at the end sorted_ids = list(x[1] for … -
Uploaded User Pic Aspect Ratio
My user model allows a user to upload a pic of themselves: class User(AbstractBaseUser, PermissionsMixin): ... picture = models.ImageField(upload_to='profile_images', null=True, blank=True) ... Not sure if the best way to go would be to make the picture a separate model... After the user is registered they can edit their profile to upload the pic. This is the clean section of the form: def clean_picture(self): picture = self.cleaned_data['picture'] if picture: try: w, h = get_image_dimensions(picture) #validate dimensions max_width = max_height = 1500 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) #validate content type main, sub = picture.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): raise forms.ValidationError(u'Please use a JPEG, ' 'GIF or PNG image.') #validate file size if len(picture) > (20 * 10024): raise forms.ValidationError( u'picture file size may not exceed 20k.') except AttributeError: """ Handles case when we are updating the user profile and do not supply a new picture """ pass image_file = io.BytesIO(picture.read()) image = Image.open(image_file) w, h = image.size image = image.resize((w//2, h//2), Image.ANTIALIAS) image_file = io.BytesIO() image.save(image_file, 'JPEG', quality=90) picture.file = image_file return picture … -
tearDown failing due to CurrentUserField
I am using CurrentUserField from django_currentuser in my Business model. I have the following model: class Business(models.Model): ... created_on = models.DateTimeField(auto_now_add=True, editable=False) created_by = CurrentUserField(null=True, blank=True, editable=False, # Attention 4 on_delete=models.SET_NULL) And I am testing this in the following test case: class Base(TestCase): def setUp(self): self.padmin = User.objects.create_user('padmin') for u in (self.padmin,): u.set_password('password') u.save() self.business = Business.objects.create(name='name', address='address', phone_number='123-456-7890') self.business2 = Business.objects.create(name='name2', address='address', phone_number='123-456-7891') def STEP_create_instance(self): self.client.login(username='padmin', password='password') url = '/' self.client.post(url, {}) # Attention: 1 class SafesiteProductionFlowIntegrationTest(Base): def test_one(self): self.STEP_create_instance() # Attention: 2 def test_two(self): self.STEP_create_instance() # Attention: 3 When I run this test, I am getting the following error: System check identified no issues (0 silenced). ..E ====================================================================== ERROR: test_before_split2 (instances.tests.test_viewflow.SafesiteProductionFlowIntegrationTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.IntegrityError: insert or update on table "businesses_business" violates foreign key constraint "businesses_business_created_by_id_25175862_fk_auth_user_id" DETAIL: Key (created_by_id)=(1) is not present in table "auth_user". The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/test/testcases.py", line 209, in __call__ self._post_teardown() File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/test/testcases.py", line 893, in _post_teardown self._fixture_teardown() File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/test/testcases.py", line 1041, in _fixture_teardown connections[db_name].check_constraints() File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 235, in check_constraints self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE') File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in …