Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django objects.filter(x__in = y) returns only unique x objects
user_identity = request.POST.get('user_id') contact_list = Contact.objects.filter(receiver_id = user_identity).order_by('-last_updated') contact_list_senders = contact_list.values_list('sender_id', flat=True) customer_list = Customer.objects.filter(customer_id__in=contact_list_senders) zipped_data = zip(contact_list, customer_list) I am getting a user_id from POST and find all the Contact objects with this user_id. Afterwards I get the sender_id of these contacts. contact_list_senders returns {sender_id1, sender_id2, sender_id1, sender_id2, sender_id1} so it has non-unique ids , which is correct because there are multiple contacts between the user_id and sender_ids. When I try to find the Customer objects from the contact_list_senders QuerySet with Customer.objects.filter(customer_id__in=contact_list_senders) Actual Output: {Customer1, Customer2} Desired Output {Customer1, Customer2, Customer1, Customer2, Customer1} I understand the actual output makes sense because there are only 2 Customer objects that matches with these contacts. Can you please help me to get the desired outcome? models.py: class Contact(models.Model): contact_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) related_complete_order = models.ForeignKey(landingpages.models.CompleteOrderList) receiver_id = models.CharField(max_length=244, blank=False, null=False) sender_id = models.CharField(max_length=244, blank=False, null=False) last_updated = models.DateTimeField() created = models.DateTimeField(auto_now_add=True) class Customer(models.Model): customer_id = models.CharField(max_length=244, blank=False, null=False) first_name = models.CharField(max_length=244, blank=True, null=True) last_name = models.CharField(max_length=244, blank=True, null=True) email = models.CharField(max_length=244, blank=False, null=False) enrollment_method = models.CharField(max_length=244, blank=True, null=False) account_balance = models.DecimalField(default=0000.00, max_digits=6, decimal_places=2) reserved_balance = models.DecimalField(default=0000.00, max_digits=6, decimal_places=2) modified = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now_add=True) -
show in string instead of integer
I have a table for Device and DeviceGroup. The relation between them is a device can be on only one group, i.e same device cannot be on more than one group. But same group can have multiple devices. For that i have designed my model as models class Device(BaseDevice): """ This stores Device """ description = models.TextField(blank=True, null=True) device_group = models.ForeignKey('DeviceGroup', null=True, blank=True) created_on = models.DateTimeField(auto_now_add=True) updated_on= models.DateTimeField(auto_now=True) class DeviceGroup(models.Model): name = models.CharField(max_length=250, blank=False, null=False) created_on = models.DateTimeField(auto_now_add=True) updated_on= models.DateTimeField(auto_now=True) serializers class DeviceSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source='token', format='hex', read_only=True) io = DeviceIOSerializer(read_only=False, many=True, required=False) class Meta: model = Device fields = ('id', 'name', 'description', 'io', 'device_group') in my api i see device group in integer as "device_group": 1. If shown in string, it should be "device_group": "personal". How can i show in string? Also is my way of showing the relation between Device and DeviceGroup right? -
Most supported/reliable package to use to generate a thumbnail from an uploaded video?
I have a Post model with a video field for video a user uploads in their post: class Post(models.Model): ... video = models.FileField(null=True, blank=True) thumbnail = #something Then in my view when the video is being uploaded: def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): instance = form_post.save(commit=False) instance.thumnnail = #something instance.save() What is the best package or method for creating a thumbnail from the uploaded video? And where in the code would I generate the thumbnail? -
Why does Django Rest Framework seem to try authenticating every request?
I'm encountering an error that shouldn't be happening at all, though it can be "resolved" by simply adding to INSTALLED_APPS (without migrate): 'django.contrib.auth', 'django.contrib.contenttypes', Based on the debug output, it seems this error is occurring because Django Rest Framework is trying to authenticate the request, which requires the Auth app, which requires Permissions, which requires ContentTypes, all of which have been removed. The APIView is using the default default settings as show: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': (), 'DEFAULT_PERMISSION_CLASSES': (), 'DEFAULT_RENDERER_CLASSES': ('common.rest.JSONRenderer',), 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'common.rest.IgnoreNegotiation', } error debug: RuntimeError at /mac/pins/ Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Request Method: GET Request URL: http://django/mac/pins/ Django Version: 1.10.5 Python Executable: /home/admin/env/bin/python3.6 Python Version: 3.6.0 Python Path: ['/home/admin/src', '/home/admin/env/bin', '/home/admin/env/lib/python36.zip', '/home/admin/env/lib/python3.6', '/home/admin/env/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6', '/home/admin/env/lib/python3.6/site-packages'] Server time: Fri, 24 Feb 2017 00:54:33 +0000 Installed Applications: ['myapp'] Installed Middleware: () Traceback: File "/home/admin/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/admin/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/home/admin/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/admin/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/admin/env/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/home/admin/env/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/admin/env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch 483. … -
How to properly configure Taiga production environment?
I am facing a similar issue as #415 and #367. I just completed installation on Ubuntu 16.04, DigitalOcean. I also followed the guide on the docs about deploying a production Taiga. When I try to connect from an external system, I get the oompa loompas error message with the Js console showing: http://138.28.207.46:8000/api/v1/ Failed to load resource: could not connect to server. If I remove :8000 from ~/taiga-front-dist/dist/conf.json I get a different error: http://138.28.207.46/api/v1/ Failed to load resource: 502 bad gateway In issue #415 and #367 they managed to fix it, but none of them described which ports from which files need to be changed. /etc/nginx/sites-available/taiga server { listen 80 default_server; server_name _; large_client_header_buffers 4 32k; client_max_body_size 50M; charset utf-8; access_log /home/taiga/logs/nginx.access.log; error_log /home/taiga/logs/nginx.error.log; # Frontend location / { root /home/taiga/taiga-front-dist/dist/; try_files $uri $uri/ /index.html; } # Backend location /api { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8000/api/v1/; proxy_redirect off; } # Django admin access (/admin/) location /admin { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8000$request_uri; proxy_redirect off; } # Static files location /static { alias /home/taiga/taiga-back/static; } # Media … -
Why Django doesn't find my template
Can't understand why Django can't find the template. blog/intro.html (project/templates/blog/intro.html) <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> {% ifis_admin %} <p>{{username}} is an admin!</p> {% endif %} <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html> views.py: from django.shortcuts import render from django.shortcuts import render_to_response # Create your views here. def intro(request): render(request, "blog/intro.html") Error:TemplateDoesNotExist at / blog/intro.html -
django-user-accounts 'WSGIRequest' object has no attribute 'user'
So im following the documentation for django-user-accounts Im getting an error message 'WSGIRequest' object has no attribute 'user' The documentation asked to put in this code MIDDLEWARE_CLASSES = [ ... "account.middleware.LocaleMiddleware", "account.middleware.TimezoneMiddleware", ... ] MIDDLEWARE_CLASSES is deprecated, so i put the two lines of code in just MIDDLEWARE. INSTALLED_APPS = [ 'account', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.staticfiles', ] MIDDLEWARE = [ "account.middleware.LocaleMiddleware", "account.middleware.TimezoneMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] root urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r"^account/", include("account.urls")), ] I ran makemigrations for accounts , and i ran migrate. The server ran just fine with no errors , but whenever i go to localhost:8000/accounts/login i either get a 404 or no attribute 'user' -
Django tests with schema - schema not found
I'm using Django 1.10.5 in a project setup with django-cookiecutter. I have a non-managed model that looks like like this: # -*- coding: utf-8 -*- from django.db import models from django.conf import settings class MyModel(models.Model): """Base AdWords account model.""" account_nm = models.CharField(max_length=255, blank=True, null=True, db_column='customer_nm') class Meta: app_label = 'mylabel' db_table = '"stage"."mytable"' managed = False if not settings.TESTING else True The managed setting is meant to create my table when I'm testing but under no other circumstances. I'm running my tests with django-pytest simply like py.test --reuse-db. My backend is Redshift for this non-managed model with django-redshift-backend. If I run the tests with only db_table = 'mytable', my table is successfully created in the public schema in my test database. If I run the tests with the db_table as shown above with the schema, I receive an error. E django.db.utils.ProgrammingError: schema "myschema" does not exist E LINE 1: CREATE TABLE "myschema"."mytable" (.... I can use this model successfully in my application with the schema specific under normal circumstances. Why am I not able to create the table in my schema while testing? -
How to pass a variable and call it from another function
I have a function shop_single in my views.py that has a variableLIST 'single_shop' that takes in shop_id as an argument from URLS.PY . How do i pass that variable 'single_shop ' to another function homepage and run another set of query on it. views.py def homepage(request): cat1 = NewShop.objects.filter(category_id=1) cat2 = NewShop.objects.filter(category_id=2) cat3 = NewShop.objects.filter(category_id=3) cat4 = NewShop.objects.filter(category_id=4) name1 = ShopCategories.objects.filter(id=1) name2 = ShopCategories.objects.filter(id=2) name3 = ShopCategories.objects.filter(id=3) name4 = ShopCategories.objects.filter(id=4) return render_to_response('index.html',{'shop_name1': name1, 'shop_name2': name2, 'shop_name3': name3, 'shop_name4': name4, 'Shop_cat1': cat1, 'Shop_cat2': cat2, 'Shop_cat3': cat3, 'Shop_cat4': cat4,},) def shop_single(request,shop_id): single_shop = NewShop.objects.filter(id=shop_id) cat1 = NewShop.objects.filter(category_id=1) cat2 = NewShop.objects.filter(category_id=2) cat3 = NewShop.objects.filter(category_id=3) cat4 = NewShop.objects.filter(category_id=4) name1 = ShopCategories.objects.filter(id=1) name2 = ShopCategories.objects.filter(id=2) name3 = ShopCategories.objects.filter(id=3) name4 = ShopCategories.objects.filter(id=4) for shop_id in single_shop: return render_to_response('shop_single.html', {'shop_name1': name1, 'shop_name2': name2, 'shop_name3': name3, 'shop_name4': name4, 'Shop_cat1': cat1, 'Shop_cat2': cat2, 'Shop_cat3': cat3,'Shop_cat4': cat4, 'shop_id': single_shop, },) else: return homepage(request) urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.homepage, name='homepage'), url(r'^about/', views.about, name='about'), url(r'^allshops/', views.allshops, name='all-shops'), url(r'^shops/(?P<shop_id>[0-9]+)/$', views.shop_single, name='single-shop') -
Wagtail indexing: Exclude some content or use queryset?
In Wagtail's documentation on ElasticSearch indexing, it seems that all instances of a given model are added to the index. But I'd like to exclude some (many) rows from being indexed, either by creating a QuerySet or by being able to set an exclude param of some kind (QuerySet would be better). Is there any way to do this? Or do I need to index WT models from outside of Wagtail? -
get OFFSET, LIMIT on query set
Do query set shops = Shop.objects.filter( id__in=list(set(shop_ids))) if kitchens: shops = shops.filter( cuisineshop__in=kitchens) if min: shops = shops.filter( delivery_price__gte=min) if max: shops = shops.filter( delivery_price__lte=max) if sort_type == 1: shops = shops.order_by('rate') if sort_type == 3: shops = shops.order_by('rate') if sort_type == 4: shops = shops.order_by('rate') shops = shops.annotate(count=Count('name')) shops = shops.all()[of:per_page] print(shops.query) There is shops = shops.all()[of:per_page] of = 5, per_page = 5 but query return SELECT `catalog_shop`.`id`, `catalog_shop`.`name`, `catalog_shop`.`time_begin`, `catalog_shop`.`time_end`, `catalog_shop`.`phone`, `catalog_shop`.`preview`, `catalog_shop`.`delivery_price`, `catalog_shop`.`min_order`, `catalog_shop`.`del_wait_time`, `catalog_shop`.`is_always`, `catalog_shop`.`is_cash`, `catalog_shop`.`is_card`, `catalog_shop`.`is_online`, `catalog_shop`.`is_points`, `catalog_shop`.`notification`, `catalog_shop`.`email`, `catalog_shop`.`rate`, `catalog_shop`.`destination`, `catalog_shop`.`description`, `catalog_shop`.`cook`, `catalog_shop`.`image_cook`, `catalog_shop`.`desc_cook`, `catalog_shop`.`shoptype_id`, `catalog_shop`.`slider_id`, COUNT(`catalog_shop`.`name`) AS `count` FROM `catalog_shop` WHERE (`catalog_shop`.`id` IN (4, 5, 6, 7, 8, 9, 10) AND `catalog_shop`.`delivery_price` <= 10000) GROUP BY `catalog_shop`.`id` ORDER BY `catalog_shop`.`rate` ASC LIMIT 5 can't understand why dosen't work offest wityh limit where LIMIT(5,5)? -
Form validation on insert vs. update
I am trying to make one form for both inserting and updating data. I have read these: Model validation on update in django django exclude self from queryset for validation In my project, however, I am not using ModelForm. forms.py: from django import forms from .models import User class SettingsForm(forms.Form): username = forms.CharField(max_length=16) first_name = forms.CharField(max_length=32) # ... and many more form fields def clean_slug(self): """Make sure that the username entered by the user will be unique in the database""" username = self.cleaned_data['username'] try: product = User.objects.get(username=username) except User.DoesNotExist: # Good, there is no one using this username pass else: # There is alreaady a user with this username raise forms.ValidationError('This username has been used. Try another.') return username The form cleaning works as intended for inserting data. However, when updating data, it complains that the username has been used (naturally, since the username already exists in the database). How do I update the data without raising ValidationError when using a Form (and without using ModelForm)? (The reasons for not using ModelForm in this case are: we may stop using the the orm, SettingsForm may contain a mix of fields from different models, some fields may be repeated hundreds of … -
Why date range return empty query?
I try to create a range for my render but i only have empty query when i use now() or date.today() for filter episode by date. models.py: class Episode(models.Model): date = models.DateTimeField(null=True, default=now) I think it's the good way : page = 0 n = now() Episode.objects.filter(date__range=[n-timedelta(days=(5*page)), n-timedelta(days=(5*(page+1)))]) <QuerySet []> But it's did not work... For info : database have episodes and values who are typed datetime.datetime : for e in Episode.objects.filter(): print(e.date) 2017-02-22 19:12:31.351811+00:00 2017-02-22 19:12:31.418354+00:00 2017-02-22 19:12:31.468889+00:00 2017-02-22 19:12:31.524925+00:00 2017-02-22 19:12:31.599978+00:00 2017-02-22 19:12:31.680029+00:00 2017-02-22 19:12:31.744071+00:00 2017-02-22 19:12:31.803611+00:00 2017-02-22 19:12:31.872156+00:00 2017-02-22 22:24:56.733546+00:00 2017-02-23 19:16:00.600644+00:00 And when i use string direclty in the range it's work... Episode.objects.filter(date__range=['2017-02-22 19:12:31.351811+00:00','2017-02-22 19:12:31.744071+00:00']) <QuerySet [<Episode: Episode object>, <Episode: Episode object>, <Episode: Episode object>, <Episode: Episode object>, <Episode: Episode object>, <Episode: Episode object>, <Episode: Episode object>]> I try to initialise variables before too... n = now() page = 0 startDate = n-timedelta(days=5*page) endDate = n-timedelta(days=5*(page+1)) Episode.objects.filter(date_adding_episode__range=[startDate, endDate]) <QuerySet []> Do you have an idear why i can filter with now or datetime and it's work with a string ? -
Django user authentication not working/not logging in
I'm going through the Tango with Django tutorial and am trying to set up user authentication, however find I cannot successfully authenticate my users on the Homepage after they have been logged in (at least, I believe they are logged in). My user_login view is def user_login(request): context = RequestContext(request) if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect('/') else: return HttpResponse("Your Rango account is disabled.") else: return HttpResponse("Invalid login details supplied.") else: return render(request, 'rango/user_login.html', {}) and in my Homepage template I have: {% if user.is_authenticated %} <h1>Rango says... hello {{ user.username }}!</h1> {% else %} <h1>Rango says... hello world!</h1> {% endif %} which should take me back to the Homepage and return 'Hello USER NAME' after a successful login, but it only returns to the Homepage and presents 'Hello World' and I don't know why. Also, if it helps, this is the main part of my user login template, user_login.html: <form id="login_form" method="post" action="/login/"> {% csrf_token %} Username: <input type="text" name="username" value="" size="50" /> <br /> Password: <input type="password" name="password" value="" size="50" /> <br /> <input type="submit" value="submit" /> </form> My debugging suggests users are … -
How do I serve static files from either gunicorn or nginx
I am playing with a docker project. Django+gunicorn in one container, nginx in another container. When I switched over from the Django dev server to gunicorn, I noticed that all my static files weren't being served. I've been trying to troubleshoot this for days thinking it was an nginx issue, but if I visit the container of Django/gunicorn (and not nginx), I also don't see static files showing up here, so this makes me think it is not an nginx issue but just a simple error in my Django settings? Django settings.py DEBUG = False STATIC_ROOT = os.path.join(PACKAGE_ROOT, "static1") STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(PACKAGE_ROOT, "static"), ] STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] nginx server { listen 80; server_name example.org; charset utf-8; location /static { alias /root/proj/proj/static; } } Note: I set this alias to /root/proj/proj/static, because this is the directory path to where static files are actually located inside the Django/gunicorn container... Am I correct in setting the alias to this path? docker-compose parentserver: build: ./parentserver expose: - "8000" links: - postgres:postgres - authserver:authserver volumes: - /usr/src/app - /usr/src/app/static env_file: .env environment: DEBUG: 'true' command: ./startup.sh nginx: build: ./nginx/ ports: - "80:80" volumes: - /www/static volumes_from: - parentserver … -
nginx - unicorn - django 502 bad gateway. Connection to project.sock failed
I just deployed my django app on Digital Ocean and I keep getting this 502 error. I've double checked all my conf files and my nginx error logs shows: connect() to unix:/root/path/project_name.sock failed (13: Permission denied) while connecting to ups$ I think that it might be a permission problem, how can I change the permission of the project_name.sock file if it's not yet there/created? Any ideas? -
Django: Download file after fetching file from S3
I have files stored in S3 that I wish to serve to the client when they click a link/button. file_path = '/tmp/' + attachment.file_name s3 = boto3.resource('s3') s3.meta.client.download_file( settings.S3_BUCKET, attachment.key, file_path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse( fh.read(), content_type="application/force-download") response['Content-Disposition'] = 'attachment; filename=' + attachment.file_name return response Ajax request to get the file on button click. function downloadAttachment(attachment_id){ $.ajax({ url: '/download-attachment/', method: 'get', data: { attachment_id, }, }); }; But when the request is done the file doesn't download. When I look at the network response and open the response on a new tab, it downloads the file. How do I implement this, so when click the link/button the file gets downloaded right away at the current page. -
Create Django Queryset from Model and ForeignKey
I want to create a queryset of the Plaque model and Veteran (ForeignKey) model into a combined queryset called queryset_list. Model class Plaque(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='plaques', default=1) group = models.ForeignKey(Group, blank=True, null=True, verbose_name='Group Name') veteran = models.ForeignKey(Veteran, blank=True, null=True) ... View def plaque_list(request): today = timezone.now().date() plaques = Plaque.objects.all() veterans = Plaque.objects.all() queryset_list = plaques | veterans # queryset_list = Plaque.objects.active().order_by('first_name') ... -
Securely encrypt integers (up to 2^48) into the shortest possible URL-safe string
In my Django application I have a hierarchical URL structure: webpage.com/property/PK/sub-property/PK/ etc... I do not want to expose primary keys and create a vulnerability. Therefore I am encrypting all PKs into strings in all templates and URLs. This is done by the wonderful library django-encrypted-id written by this SO user. However, the library supports up to 2^64 long integers and produces 24 characters output (22 + 2 padding). This results in huge URLs in my nested structure. Therefore, I would like to patch the encrypting and decrypting functions and try to shorten the output. Here is the original code: # Remove the padding after encode and add it on decode PADDING = '==' def encode(the_id): assert 0 <= the_id < 2 ** 64 crc = binascii.crc32(bytes(the_id)) & 0xffffff message = struct.pack(b"<IQxxxx", crc, the_id) assert len(message) == 16 cypher = AES.new( settings.SECRET_KEY[:24], AES.MODE_CBC, settings.SECRET_KEY[-16:] ) return base64.urlsafe_b64encode(cypher.encrypt(message)).rstrip(PADDING) def decode(e): if isinstance(e, basestring): e = bytes(e.encode("ascii")) try: e += str(PADDING) e = base64.urlsafe_b64decode(e) except (TypeError, AttributeError): raise ValueError("Failed to decrypt, invalid input.") for skey in getattr(settings, "SECRET_KEYS", [settings.SECRET_KEY]): cypher = AES.new(skey[:24], AES.MODE_CBC, skey[-16:]) msg = cypher.decrypt(e) crc, the_id = struct.unpack("<IQxxxx", msg) if crc != binascii.crc32(bytes(the_id)) & 0xffffff: continue return the_id raise ValueError("Failed … -
How can I make an ajax routing with assigned urls in Django?
Creating a website that uses AJAX views with assigned urls in Django Hey I'm traying to make a website with ajax views and I would like that each view had an url assigned, making possible to the user to write the url assigned and access to the ajax view What I have read is that you need a setting like this: website --- javascript file --- json or xml file ---- a django file like urls.py So that the user send an order trough javascript , which is captured by the json or xml , and then goes to the .py file , which sends in and inversed way an answer that is the corresponding view My setup So I have the next files My project folder is named test800, and the app I created is named "thewebsite" test800 (main folder) ----test800 ----thewebsite (my app) ----db.sqlite3 ----manage.py Now inside the "thewebsite" folder: _pycache_ migrations static templates _init_.py admin.py apps.py models.py tests.py urls.py views.py Inside urls.py from django.conf.urls import url from thewebsite import views urlpatterns = [ url(r'^$', views.HomePageView.as_view(), name='home'), # Notice the URL has been named url(r'^about/$', views.AboutPageView.as_view(), name='about'), ] Inside the views.py from django.shortcuts import render # Create your … -
Django issue with loading django-disqus comments in local system
I was trying out django-disqus module on django version: 1.10.5 and django-disqus version: 0.5. I have followed the documentation correctly and set the required variables and url correctly. I am on the local machine and I have also put the tag {% discus_dev %} for development as mentioned in the docs. But when I try to view the page for comments, I get the disqus loader icon but no comment loads and get the message stating "We are unable to load Disqus". Upon examining the page source I see this "var disqus_url = '//somedomaintest.com/'" in the script tag. Which is not proper cause of the '//' at start of the url? I have added a the url as vandykfernandestest.com but when I load the page those two '//' are added automatically. Why does this happen? Is this the reason why disqus this does not load? Disqus docs clearly states it need true urls like www.somedomain.com or somedomain.com. Please let me know if anyone can help me regarding this issue. Its a local development setup so domain name should not be an issue i feel. enter image description here This is the screenshot of the page source. http://pasteboard.co/3N2ozETYR.png I have used … -
Simple Search throws up error django
I am trying out my first Django app. Previously I built the following app using Flask and it worked. I want my app to search github and return top 5 search items. My app is called assign1. The assign1/views.py is as follows from django.shortcuts import render from django.template import loader from .application import getresult # Create your views here. from django.http import HttpResponse def index(request): return render(request, 'index.html') def search(request): search_term = request.GET['search_term'] t = loader.get_template('result.html') c = Context({'items':getresult(search_term),'search_term':search_term,}) return HttpResponse(t.render(c)) The assign1/urls.py is as follows: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^result/$', views.search, name='search'), ] My assign1/templates/index.html <!DOCTYPE html> {% block content %} <div class = "container"> <h1>Search Github</h1> <form action='/assgn1/result'> <input type='text' name='search_term'><br> <br><br> <input type='submit' value='Submit'> </form> {% endblock %} My result.html is as follows: <!DOCTYPE html> <head><title>Github Navigator</title></head> <body> {% block content %} <h1>{{search_term}}</h1> {% for rep in items %} <h2>{{loop.index}} {{rep["respository_name"]}}</h2> <h3> Created {{rep["created_at"]}}</h3> <a href="{{rep["owner_url"]}}"><img src="{{rep["avatar_url"]}}" alt="avatar" height="42" width="42"/></a> {{rep["owner_login"]}} <h3>LastCommit</h3> {{rep["sha"]}} {{rep["commit_message"]}} {{rep["commit_author_name"]}} <hr/> {% endfor %} {% endblock %} </body> The index opens fine. When I click the button, the website url is http://127.0.0.1:8000/result?search_term=arrow I get an error saying Page not found Using the … -
Trying to serialize geometry data in python from several many-to-one django models to json
I have some models that are pretty straight forward in their relationship: class CesiumEntity(models.Model): be_number = models.CharField(max_length=100) #the number assigned to a foot print to distinguish zone_id = models.ForeignKey('ZoneEntity', null=True, blank=True) .... and class ZoneEntity(models.Model): zone_number = models.CharField(max_length=100, primary_key=True) #zone_number = models.CharField(max_length=100) mpoly = models.PolygonField() #this should grow and shrink for the most representative one... objects = models.GeoManager() created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) I am trying to get data from them as a join: object_list = ZoneEntity.objects.filter(cesiumentity__sensor__in=sensor).distinct('zone_number') (Which should be equivalent to the sql: SELECT distinct(zone_number) FROM SWSITE_ZONEENTITY INNER JOIN SWSITE_CESIUMENTITY ON SWSITE_ZONEENTITY.zone_number = SWSITE_CESIUMENTITY.zone_id_id WHERE SWSITE_CESIUMENTITY.sensor = 'RADARSAT-2' So this gives me all these zone numbers based on a sensor that is selected on the UI. This is great, for each zonenumber there are many of the other things (CesiumEntities). So I want to roll all that up as a json object to send back to my web interface. Something like this ZoneEntity.ZoneNumber ZoneEntity.mpoly (Geometry) List of all cesiumentities which zone_id_id = zoneNumber I can get this data have the code to do it: returnData = [] secondData =[] object_list = ZoneEntity.objects.filter(cesiumentity__sensor__in=sensor).distinct('zone_number') print len(object_list) for ze in object_list: second_list = CesiumEntity.objects.filter(zone_id = ze.zone_number) returnData.append(ze.zone_number) returnData.append(ze.mpoly) for sl in second_list: secondData.append(sl.sensor) secondData.append(sl.resource_location) secondData.append(sl.name) … -
order admin list by username
I want to order the users list by username. This is not working. from django.contrib.auth.models import User class UserAdmin(admin.ModelAdmin): ordering = ['username'] admin.site.unregister(User) admin.site.register(User, UserAdmin) The code is executing because if I remove the register method, it throws an error. I need to do this because I have another admin with: list_filter = [ 'user', 'content_type', 'action_flag' ] and username here is not being ordered, so it is almost imposible to search a user. I'm using django 1.8 -
How do I set a default, max and min value for an integerfield Django?
from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class Match(models.Model): . . . overs = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)]) I've tried using the PositiveIntegerField but I believe that you cannot set a max value for that through Django - I'm not sure.