Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can i deploy a django web app on a web server i can't configure?
So we got a project at uni to create a website. We have not received any specific on what technologies to use, we were only given a theme. These projects will end up hosted on the uni website. The host for the website is: http://uni.co.uk The projects will end up at the url: http://uni.co.uk/module_code/projects/ Normally, the tutor expects just a front-end solution with a bundle of html, css and javascript files. I would like to add some back-end to make the website dynamic. I have played around with Django and node.js and I quite fancy Django and want to give it a try for this project. My only issue is that the web server my project will end up on is not accessible to me and I can't configure it. Is there any way I can still use some back-end in my project if I cannot access the main host web server configuration ? Any way I can create my own tiny web server at that url where my project ends up ? Not expecting any code solutions, if someone could just tell me if this is possible and point me to the right resource for information. I do apologize … -
Django Admin Inline Translation
Apologies if there is a similar question, I was having a hard time finding one to work out right. I am building an API with Django Rest Framework that will serve multiple languages. I have built in translations using the modeltranslation package, and it works well. Each of my users has a language specified to them, such as 'en' for English and 'no' for Norwegian. I am wanting to make my inline for a model choose the correct language for the user. Does anybody know how I can get this to work? Here is an example of code to more clearly demonstrate: Please note that I have a Dish Model where name and instructions have both translations: class Dish(models.Model): name = models.CharField(max_length=128) instructions = models.TextField(blank=True) food = models.ManyToManyField('Food', through='DishIngredient') user = models.ForeignKey(User, blank=True, null=True, default=None) I have a Food Model where name has translations: class Food(models.Model): name = models.CharField(max_length=128) And finally a DishIngredient Model: class DishIngredient(models.Model): food = models.ForeignKey('Food', on_delete=models.CASCADE) dish = models.ForeignKey('Dish', on_delete=models.CASCADE) quantity = models.FloatField() Now, in my admin.py page, I have: class DishAdmin(TranslationAdmin): model = Dish list_display = ['name_en', 'name_no'] inlines = [FoodQuantityInline] class FoodQuantityInline(admin.TabularInline): model = DishIngredient This works to show the proper dish ingredients in … -
How to use a function to pass the result to 'queryset'?
I'm working on a Python/Django project. I have to use the YearArchiveView base class, so I have this: class ArchiveView(YearArchiveView): queryset = ArticlePage.objects.all() make_object_list = True date_field = 'date' template_name='btcmag/pages/archives_list.html' allow_future = False context_object_name = 'articles' def extract_month(self, article): 'extracts the starting date from an entity' return article.date.month def extract_year(self, article): 'extracts the starting date from an entity' return article.date.year Instead of having queryset = ArticlePage.objects.all(), I would like to have a function returning the correct Queryset. Something like: queryset = getQuerySet() At the same time I have to pass in some parameters. I tried defining the function within the class, calling it with self and alone, but no luck. Where do I have to define the function/method? How can I pass it to queryset? -
Verifying text is present on web page
I am trying to perform behavior tests using django-behave against selenium. I am fairly new to behavior tests and because of my lack of experience, what I tried was: @then(u'is {thing} present') def step_impl(context, thing): #testing other things assert_true("text" in context.driver.page_source) This did not seem to work for multiple reasons. Firstly, I get the error AttributeError: 'PatchedContext' object has no attribute 'driver', which tells me my whole idea is wrong. Secondly, even if this worked, I wouldn't be capable of testing all of my pages with just this test, as I have to specifically give the "text" that I want to verify if present. Is there a way to test this with only 1 assertion? -
How to delete an object after 24hrs since creation of the same
I want to delete an instance after 24 hours since that instance has been created how to do that with celery How can i start the "TIMER" after the creation of an instance? I want something like Snapchat -
django user followers retrival from database
I have an application with a user follower system which I have been able to achieve but I try to retrieve individual user followers and following but I could not get it. Below is my code View.py def following(request): query = Profile.objects.filter(request.user.following) context = { 'query': query } template = 'following.html' return render(request, template, context) additional codes would be added on request. -
Django QuerySet API inverse field lookup
I'm wondering if it is somehow possible to use "the inverse" of the __contains fields lookup. https://docs.djangoproject.com/en/1.11/ref/models/querysets/#contains So for example: class Person(models.Model): ... last_name = models.CharField() And with this Person model I could do for example the following query that'll return the Persons that have a last_name field that would fit in the string given: >>> Person.objects.filter(last_name__contains='John Doe, Jane Roe, ...') <QuerySet: [Person: Donald Doe]> -
Using WhiteNoise with Django to serve directories of HTML files
I'm using Whitenoise successfully to serve all my Django site's static files under a /static/ path. I'd also like to have a couple of other directories of HTML files, images, etc served at different paths (e.g. /foo/my_file.html and /bar/hello.html). I think Whitenoise lets you add further directories using add_files() but I can't figure out how to use this with a Django site that's using the DjangoWhiteNoise class, and with a wsgi.py that currently looks like: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") application = get_wsgi_application() Has anyone done something like this? -
Is it possible for a queryset filter to not work properly? Django 1.11.12
I ran the code below... and somehow... I got a couple of campaigns that were not active and were passed into the update_existing_campaigns. I am a little mindblown as to how this happened... it was also only a couple of inactive campaigns that were passed in, not all of them. How is this possible? all_campaigns = AdCampaign.objects.all() active_campaigns = AdCampaign.objects.filter(active=True) update_existing_campaigns(active_campaigns) -
Django Using Slug Field for Detail URL
I'm attempting to setup my site so that the url for my job-detail will use a slug field instead of a pk. It's telling me that it cannot find my job with the given slug (which is an int, 147). urls: urlpatterns = [ url(r'^careers$', views.job_list, name='job-list'), url(r'^careers/(?P<slug>[0-9]+)/$', views.JobDetailView.as_view(), name='job-detail'), ] view: class JobDetailView(CacheMixin, DetailView): model = Job pk_url_kwarg = 'slug' def get_object(self, *args, **kwargs): # Call the superclass object = super(JobDetailView, self).get_object() # Return the object return object def get(self, request, *args, **kwargs): object = super(JobDetailView, self).get(request, *args, **kwargs) return object model: class Job(UpdateAble, PublishAble, models.Model): slug = models.CharField(unique=True, max_length=25) facility = models.ForeignKey('Facility') recruiter = models.ForeignKey('Recruiter') title = models.TextField() practice_description = models.TextField(blank=True, default="") public_description = models.TextField(blank=True, default="") objects = JobManager() def get_next(self, **kwargs): jobs = Job.objects.published() next = next_in_order(self, qs=jobs) if not next: next = jobs[0] return next def get_prev(self, **kwargs): jobs = Job.objects.published() prev = prev_in_order(self, qs=jobs) if not prev: prev = jobs[len(jobs)-1] return prev def __str__(self): return f'{self.facility}; {self.title}' manager: class JobManager(models.Manager): def published(self): return super(JobManager, self).get_queryset().filter(is_published=True).order_by('facility__name', 'title') -
Sending an email from python (purchased from wix)
A client of mine has recently decided to get his domain and email packages from Wix, and then decided to use that domain with a Django/python application. I cannot find a quick way to send an email using a python script, I have tried to use the same gmail settings to no avail. Is there a tutorial somewhere that I can follow? has anyone accomplished that before? -
Can't connect to docker from Django, but can connect directly and in shell
I have a Python/Django app that allows users to manage docker instances (with some abstraction). I can control the docker containers from bash and from the Django shell just fine, but when I try to run the same code from my Django views, which are running through Gunicorn as the same user as I am running bash and the Django shell from, but Gunicorn gives the following output: ERROR while fetching server API version: ('Connection aborted.', error(13, 'Permission denied')) The user that Gunicorn is running under is a member of the "docker" group, and I've restarted my server to be sure that the permissions should be in affect. I'm not sure what else to check or do. -
how to run popen in django with apache?
I met problem when try to upload file from my web server to s3. django 1.7.8 + python 2.7 os.popen(asw s3 cp c:\1.txt s3://bucket) The popen run well in my develop env(VS code, debug running ok) no apache. But it seems not run at all on product env, which apache hosts. Any body has some ideas? Thank you so much! -
Django: stop resubmit duplicate data when many time press enter key within keyboard
I created a form for data submission. When a user successfully fillup that form, I am using HTTP redirect method. Now Everything is okay and data do not resubmit when user want to page refresh. But user fillup that form and press Enter key again and again. Same data added how much user press Enter key button. I want to stop that. A user can be press Enter key onetime. Data do not add in the database if a user will press Enter Keyboard second or more time. this is my form html file {% extends "shop/base.html" %} {% block content_area %} <div class="row"> <div class="col-lg-5"> <p>Customers Details</p> <hr> <div class="customers_info_due"> <p>Invoice ID: : {{due_customers.customer_uid}}</p> <p>Name: {{due_customers.customer_name}}</p> <p>Product Name: {{due_customers.customer_product_name}}</p> <p>Price: {{due_customers.customer_price}} TK</p> <p style="color:red">Customer Paid First Time: {{due_customers.customer_first_time_payment}} Taka</p> {% if track_invoice %} <table class="table"> <thead> <tr> <th>SL</th> <th>Paid Taka</th> <th>Paid Date</th> </tr> </thead> <tbody> {% for x in track_invoice %} <tr> <td>{{forloop.counter}}</td> <td>{{x.customer_due}}</td> <td>{{x.customer_due_date}}</td> </tr> {% endfor %} <tr> <td> Total</td> <td><b>{{sum_cost_taka}}</b> TK </td> </tr> </tbody> </table> {% else %} {% endif %} <p>WARRENTY: {{due_customers.customer_product_warrenty}}</p> <p>QN: {{due_customers.customer_product_quantity}}</p> <p>Mobile No: {{due_customers.customer_mobile_no}}</p> <p>Sell Date: {{due_customers.customer_sell_date}}</p> </div> </div> <div class="col-lg-6"> <p>Update customers due info</p> <hr> <div class="due_forms"> <form action="{% url "shop:dueupdate" … -
Powershell LDAP Bind
I've wrote a Python app that successfully binds and connections to my LDAP server. However, I want to run a command to sync the LDAP users with my user database, using the following: python manage.py ldap_sync_users When I attempt to run the command it states: raise LDAPOperationResult(result=result['result'], description=result['description'], dn=result['dn'], message=result['message'], response_type=result['type']) ldap3.core.exceptions.LDAPOperationsErrorResult: LDAPOperationsErrorResult - 1 - operationsError - None - 000004DC: LdapErr: DSID-0C0907C2, comment: In order to perform this operation a successful bind must be completed o n the connection., data 0, v2580 - searchResDone - None My question is how can I bind to the LDAP connection in powershell prior to running my python script? -
Unable to understand the flow of list serializer update in django rest framework
I am using list Serializer by many = True. The create method is running perfectly but i am unable to understand the flow of custom update method of list serializer in documentation of django rest framework. Using the base of list serializer is clear but when i am using it in code the flow is not understandable. I am not able to understand what book.items mean in the fourth line. What is book ? In the documentation it is also asking to add an explicit id field to the instance serializer. The default implicitly-generated id field is marked as read_only. Looking to understand what documentation is saying and how to implement it. The context from documentation is give below. class BookListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): # Maps for id->instance and id->data item. book_mapping = {book.id: book for book in instance} data_mapping = {item['id']: item for item in validated_data} # Perform creations and updates. ret = [] for book_id, data in data_mapping.items(): book = book_mapping.get(book_id, None) if book is None: ret.append(self.child.create(data)) else: ret.append(self.child.update(book, data)) # Perform deletions. for book_id, book in book_mapping.items(): if book_id not in data_mapping:a book.delete() return ret -
Django: Quickfix to pass JSON values from view to template
Good day SO, this is not a question per-se, but a quickfix solution I found while learning how to use Django and Python. I figured it might help someone else so here it goes.. I want to pass a queryset onto a ListView (I made an auto-refreshing div via jquery) and wanted to pull updated data in JSON every few seconds. Here is my view.py: import json from django.core import serializers from django.template import loader from django.views.generic.list import ListView from .models import * class getSomeJson(ListView): template_name='divPortionToRefresh.html' def get_context_data(self, **kwargs): find_id = self.kwargs['slug'] updateItem = Model.objects.filter(Model_ID=find_id) context = { 'jsonData': serializers.serialize('json', updateItem) } return context Here is my HTML portion: <script text="text/javascript"> var rawData = {{ jsonData|safe }}; </script> I hope I helped someone somewhere.. :) Have a nice day SO! -
Django Restful API Get Request Returns Nothing
I am trying to test the output of my APIs. class TestApiStatusCode(TestCase): client = APIClient() def test_urls(self): response = self.client.get('/api/total-fund-aum') print(response.content) self.assertEqual(response.status_code,200) However, when I try to print the response.content, I get this output: b'[]'. From my browser, data is being returned however. Why is this the case? I am using django-rest-framework -
Django Rest Framework serializers allow dotted notation
I'm using Django 1.11 and Django Rest Framework to make an REST API. I have models as: class Product(models.Model): ... class Image(models.Model): product = ForeignKey(Product) when i'm creating a POST request to create new product ( Content-Type: multipart\form-data]) i have to use the notation: images[0]image : <SOME_IMAGE_FILE> images[1]image : <SOME_IMAGE_FILE> Is there a way to use a dotted notation like: images.0.image : <SOME_IMAGE_FILE> images.1.image : <SOME_IMAGE_FILE> Should i create a custom parser ( http://www.django-rest-framework.org/api-guide/parsers/ ) ? -
Django Test API Output
I want to test the output of some API urls. Currently my code tests the status_codes of these API urls. class TestApiStatusCode(TestCase): client = Client() def test_urls(self): response = self.client.get('/api/total-fund-aum') self.assertEqual(response.status_code,200) But how can I get the output of the api urls? -
Vue and Django Development Environment
I just started a new little project for learning purposes and I want to try out Vue js with Django (with DRF). I'm trying to use vue loader (webpack-simple template). The problem is that I don't know how to synchronize npm run dev and python manage.py runserver. I don't know how to access a template that is rendered by django in webpack-dev-server. I mean I have a template with django-template specific keywords like {% load static %} that is not handled by webpack-dev-server, obviously. I know I can build it everytime npm run build, but that's kinda annoying and boring to wait for it everytime I want to make a little change. In webpack, it's specified to run on a default index.html file, how can I make it work on the template that is actually rendered in 127.0.0.1:8000 with python manage.py runserver running? Is there an alternative? Thanks in advance for answers! -
RuntimeError: Model class __main__.category doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
i have seen many questions regarding this error but still i cant solve this error i have created an app called website and configured model.py import os import sys from django.db import models if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tango.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) class category(models.Model): name=models.CharField(max_length =128,unique=True) def __str__(self): return self.name class page(models.Model): category=models.ForiegnKey(category) title= models.CharField(max_length=128) url=models.URLField() views=models.IntegerField(default=0) def __str__(self): return self.title this is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', ] and when i tried to run the command python manage.py migrate iam getting an error Traceback (most recent call last): File "manage.py", line 24, in <module> class category(models.Model): File "C:\Users\madhumani\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 118, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class __main__.category doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. please … -
DRF Serializer handling generated field
I have a Django model that has two required fields - name and a slug. The slug could be passed in during the POST request or otherwise can be generated from name. I then have a model Serializer with both slug and name fields. If the slug is not passed in it throws an error that slug is a required field. However, I want to make it so that if slug is not passed in, I generate it from the name that is always passed in. Is there a way to do this gracefully in Serializer? -
How to set image from models in css django 1.11.x?
I try insert a image previously registred by user in css file. My model class Basics(models.Model): ... logo = models.ImageField('Logo') ... My context_processors # -*- conding:utf-8 -*- from .models import Basics def general(request): try: sitebasics = Basics.objects.get(pk=1) except: sitebasics = False context = { 'sitebasics': sitebasics, } return context My css file {% load thumbnail %} ... .header-full-title { float: left; overflow: hidden; padding-left: 75px; background-image: url("{{ sitebasics.logo|thumbnail_url:'logo_large' }}"); background-repeat: no-repeat; background-position: left center; } And the output inspecting the HTML is: .header-full-title { float: left; overflow: hidden; padding-left: 75px; background-image: url({{ sitebasics.logomarca|thumbnail_url:'logo_large' }}); background-repeat: no-repeat; background-position: left center; So when render it don't put the path of image, puts {{ sitebasics.logomarca|thumbnail_url:'logo_large' }} raw text from css. How I did to load a image in css file when render HTML? -
Django-datatable-view throwing error after decorating url
I am using django-datable-view for rendering data from django models. Everything works fine before decorating the url, after i added login_required to the url, it threw weird error. According to the doc, it states that i can add login_required to the url. Below is my code from django_datatables_view.base_datatable_view import BaseDatatableView class OrderListJson(BaseDatatableView): # The model we're going to show model = MyModel # define the columns that will be returned columns = ['number', 'user', 'state', 'created', 'modified'] # define column names that will be used in sorting # order is important and should be same as order of columns # displayed by datatables. For non sortable columns use empty # value like '' order_columns = ['number', 'user', 'state', '', ''] # set max limit of records returned, this is used to protect our site if someone tries to attack our site # and make it return huge amount of data max_display_length = 500 def render_column(self, row, column): # We want to render user as a custom column if column == 'user': return '{0} {1}'.format(row.customer_firstname, row.customer_lastname) else: return super(OrderListJson, self).render_column(row, column) def filter_queryset(self, qs): # use parameters passed in GET request to filter queryset # simple example: search = self.request.GET.get(u'search[value]', None) …