Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to manually create tags using Bootstrap Tags Input
I am using Bootstrap Tags Input for introducing tagging mechanism in my project. So far I can easily load predefined tags using add method as described in the documentation, But I am unable to create tags manually. Say I type some text and press space or comma button then a new tag should be created, Just like we add tags while writing Stack overflow question. Is it possible to add this behaviour, any help would be appreciated. -
'update_grid' object has no attribute 'title'
I have written model.py and views.py.When I add the json variable from Admin it gives following error 'update_grid' object has no attribute 'title' My views.py def save_grid(request): if request.method == 'POST': data = json.loads(request.body) grid = update_grid(data=data) grid.save() return HttpResponse('success') # if everything is OK My models.py from django.db import models from django.utils import timezone from jsonfield import JSONField class update_grid(models.Model): data = JSONField() def __str__(self): return self.title My JSON variable is of the form [{"col":1,"row":1,"size_x":1,"size_y":1},{"col":2,"row":1,"size_x":1,"size_y":1},{"col":3,"row":1,"size_x":1,"size_y":1},{"col":4,"row":1,"size_x":1,"size_y":1},{"col":1,"row":2,"size_x":1,"size_y":1},{"col":2,"row":2,"size_x":1,"size_y":1},{"col":3,"row":2,"size_x":1,"size_y":1},{"col":4,"row":2,"size_x":1,"size_y":1},{"col":1,"row":3,"size_x":1,"size_y":1},{"col":2,"row":3,"size_x":1,"size_y":1},{"col":3,"row":3,"size_x":1,"size_y":1},{"col":4,"row":3,"size_x":1,"size_y":1},{"col":5,"row":1,"size_x":1,"size_y":1},{"col":6,"row":1,"size_x":1,"size_y":1}] -
Django querying user_auth with each request
When I login and visit any page, Django will proceed to do this query everytime: SELECT ••• FROM "auth_user" WHERE "auth_user"."id" = '1' How can I stop it? I am already saving the session in cache, I have also deleted all tags that use request and nothing happens, django will still make the query, only time it does not make the query is when I am an AnonymousUser. Version of django is: 2.0.2 -
how to get all values of primary key related field nested serializer django rest framework
I have the following models: class SearchCity(models.Model): city = models.CharField(max_length=200) class SearchNeighborhood(models.Model): city = models.ForeignKey(SearchCity, on_delete=models.CASCADE) neighborhood = models.CharField(max_length=200) and then the following nested serializer: class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer): searchneighborhood_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = SearchCity fields = ('city','searchneighborhood_set') read_only_fields =('city', 'searchneighborhood_set') paired with the view: class CityNeighborhoodView(ListAPIView): queryset = SearchCity.objects.all() serializer_class = CityNeighborhoodReadOnlySerializer when I make the api call I get this: city: "Chicago" searchneighborhood_set: 0: 5 1: 4 2: 3 city: "New York" searchneighborhood_set: 0: 8 1: 7 2: 6 Im just getting the primary keys of the objects related. Which is good I need that, but I also want the neighborhood name how do I get that? -
How to get all coordinates under a boundary in Google maps API and django
I've Coordinate data associated with a post what I want is that, let's say someone posted a post with coordinated of some coffee shop Manhattan, I wanna get that post while querying New York. One way I can think of to tackle this problem is to get all coordinates under New York and search it that way I know it's very stupid but I can't think of any other way. -
Download specific file after submiting key Django
I want to ask user about previously generated key to grand him permission to download a file from the server. The key is being kept in database. My template is supposed to display all available files in the folder, ask for the key and return user to the url with auto download response with specific file, if the validation based on given key succeeded. Unfortunately I struggle with put all things together. # views.py which is supposed to check for everything # ATM it doesn't check anything, just prepared query for the validation def list(request): folder = settings.MEDIA_ROOT file_list = os.listdir(folder) form = KeyForm(request.POST) if request.method == 'POST': if form.is_valid(): secret = form.cleaned_data['secret_key'] obj = Items.objects.get(secret=secret) return render_to_response('list.html', {'form': form, 'file_list': file_list}) return render(request, 'list.html', {'form': form, 'file_list': file_list}) #function which wrapps the file and return response with the file def download_file(request, file_name): file_path = settings.MEDIA_ROOT + file_name wrapper = FileWrapper(open(file_path, 'rb')) response = HttpResponse(wrapper, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=' + file_name return response # list.html <body> {% for file in file_list %} <form action="/download/{{ file }}" method="post">{% csrf_token %} {% endfor %} <select name="file" id="file"><br> {% for file in file_list %} <option value="{{ file }}">{{ file }}</option> {% endfor … -
Django-debug-toolbar shows duplicates in sql queries, how bad is it to have duplicates?
django-debug-toolbar showed this message: 392.81 ms (263 queries including 255 duplicates ) how bad is it to have a lot of duplicates, and how can i prevent it? Thank you -
paging through cql query on django
I have two queries. One that gives me the first page from a cassandra table, and another one that retrieves the successive pages. The fist one is like : select * from images_by_user where token(iduser) = token(5) limit 10 allow filtering; The successive ones are : select * from images_by_user where token(iduser) = token(5) and imagekey > 90b18881-ccd3-4ed4-8cdf-d71eb99b3505 limit 10 allow filtering; where the image key is the last one on the first page. I have 13 rows in the table. The first query returns 10 both on the cqlsh and the application (consistency level ONE just for development). The second query only retrieves results on clash. Below is the cassandra database engine configuration I have on the django application : 'ENGINE': 'django_cassandra_engine', 'NAME': 'xekmypic', 'HOST': 'localhost', 'OPTIONS': { 'replication': { 'strategy_class': 'SimpleStrategy', 'replication_factor': 1 }, 'connection': { 'consistency': ConsistencyLevel.LOCAL_ONE, 'retry_connect': True # + All connection options for cassandra.cluster.Cluster() } } The cassandra version I am using is doc-3.0.9 and below is my virtual env pip list : cassandra-driver (3.9.0) Cython (0.25) Django (1.11) django-cassandra-engine (1.1.0) mysqlclient (1.3.10) olefile (0.44) Pillow (4.1.0) pip (7.1.2) python-memcached (1.58) pytz (2017.2) setuptools (18.2) six (1.10.0) Why does the second page does not return … -
Django create multy file field
Sorry for my english. I need create multy file field for upload pdf and images. I dont know, i correct did it or not. Please give me some i have not model, it my serializer: class MultyFieldSerializer(serializers.Serializer): attachments = serializers.ListField( child=serializers.FileField(max_length=100000, allow_empty_file=False, use_url=False) ) my question. Is this correct fileld for upload file in server? -
Random HTTP 500 error Django
Ive been having an issue with a HTTP 500 error , doesn't seem to cause any real problems until a few hours after the error has showed, the script begins to act abnormally when trying to toggle a relay( which is one of its functions) i checked my logs both in the pi and the server side these are what i found On the pi: tail applocation/errors.log 2018-03-05 06:38:33 [HTTP Error] While sending data to remote Server: HTTP Error 500: Internal Server Error 2018-03-05 09:08:50 [HTTP Error] While sending data to remote Server: HTTP Error 500: Internal Server Error on the server: This is where it gets weird because most of the time it returns 200 but like i said every so often i gives a 500 error cat /var/log/ngnix/access.log | grep 9:0 47.176.12.130 - - [05/Mar/2018:09:08:29 -0800] "POST /api/1.0/access/add/ HTTP/1.1" 200 43 "-" "Python-urllib/3.4" 47.176.12.130 - - [05/Mar/2018:09:08:50 -0800] "POST /api/1.0/access/add/ HTTP/1.1" 500 38 "-" "Python-urllib/3.4" 47.176.12.130 - - [05/Mar/2018:09:09:28 -0800] "POST /api/1.0/access/add/ HTTP/1.1" 200 43 "-" "Python-urllib/3.4" cat /var/log/ngnix/access.log | grep 500 raspberry.pi.ip - - [05/Mar/2018:06:38:33 -0800] "POST /api/1.0/access/add/ HTTP/1.1" 500 38 "-" "Python-urllib/3.4" raspberry.pi.ip - - [05/Mar/2018:09:08:50 -0800] "POST /api/1.0/access/add/ HTTP/1.1" 500 38 "-" "Python-urllib/3.4" in my … -
Setup Nginx as a proxy to Nuxtjs and Django
I have a web project working locally in my machine. I am using Django for the backend, and Nuxtjs (vuejs server side rendering framework). Nuxtjs communicate to Django with the API. Django is running on a Vagrant machine on port 0:80, and Nuxtjs is running on my localhost:3000. Both are working fine. Now I would like to deploy it on a VPS, and would like to setup Nginx as the reverse proxy for the app. I know how to run Django with Gunicorn and Nginx as the proxy. But, how can I configure Nginx to run Nuxtjs (node server) on the front-end, and Django as its backend. I hope I was clear, and if not please ask. Thank you. -
Do all tables need to be built as models?
I am new to Django and trying to figure out models. I have a question that I just cannot find the answer to. I am designing an equipment checkout app. I would like to have a data entry page (/Admin) where we can enter the equipment names and types...no problem (I think). However, I also need a Checkout table that will be updated as equipment is checked in and out and an Employee table that would hopefully pull from AD. My question is, do these two tables that will not be updated manually on the Admin page still need to be defined as models? Is this where the 'EDITABLE' field option comes in? Thanks! -
django ajax return more than one piece of html and mount
Because of a limitation in bootstrap modals that they need to be outside a postion: fixed, I need to return 2 separate pieces of html in django after an ajax response (a list of items and their modals) Is there a way in django to return 2 pieces of redendered html? Currently I have in the ajax view I return a single piece of html with: return render(request, 'pages/quotes_results.html', context) which I mount with: $.ajax({ url: '/users/some_ajax_view/', data: { 'filters': filters }, success: function (data) { $('.ajax-block').html(data) } }) -
Django executing tests for app not in INSTALLED_APPS
Under my Django project there are a few apps and all of them have unit tests. One of them that I'm working right now is supposed to be included only in dev/stage environments, so I'm enabling it using a environment variable. When this variable is present it is added to INSTALLED_APPS and it is working just fine, the problem is that Django is executing the tests for this app even when it is not in INSTALLED_APPS, and it fails with the following message: ImportError: Failed to import test module: debug.tests.unit.test_services` ...(traceback information)... RuntimeError: Model class debug.models.Email doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. When I define the app_label in the class Meta of models in this app the error is different, it says it can't find a table, I assume that this is because the app is not in INSTALLED_APPS, so it's migrations are not executed. OperationalError: no such table: debug_email I'm not sure why Django executes the tests for all apps, but not it's migrations. Am I missing something from Django configuration for tests? -
Celery and Django, queries cause ProgrammingError
I'm building a small Django project with cookiecutter-django and I need to run tasks in the background. Even though I set up the project with cookiecutter I'm facing some issues with Celery. Let's say I have a model class called Job with three fields: a default primary key, a UUID and a date: class Job(models.Model): access_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) date = models.DateTimeField(auto_now_add=True) Now if I do the following in a Django view everything works fine: job1 = Job() job1.save() logger.info("Created job {}".format(job1.access_id)) job2 = Job.objects.get(access_id=job1.access_id) logger.info("Rertieved job {}".format(job2.access_id)) If I create a Celery task that does exactly the same, I get an error: django.db.utils.ProgrammingError: relation "metagrabber_job" does not exist LINE 1: INSERT INTO "metagrabber_job" ("access_id", "date") VALUES ('e8a2... Similarly this is what my Postgres docker container says at that moment: postgres_1 | 2018-03-05 18:23:23.008 UTC [85] STATEMENT: INSERT INTO "metagrabber_job" ("access_id", "date") VALUES ('e8a26945-67c7-4c66-afd1-bbf77cc7ff6d'::uuid, '2018-03-05T18:23:23.008085+00:00'::timestamptz) RETURNING "metagrabber_job"."id" Interestingly enough, if I look into my Django admin I do see that a Job object is created, but it carries a different UUID as the logs say.. If I then set CELERY_ALWAYS_EAGER = False to make Django execute the task and not Celery: voila, it works again without error. But running … -
Django subquery with ManyToMany
I have the following database schema: class Psychologist: availabilities = models.ManyToManyField(Availability, blank=True) taken_availabilities = models.ManyToManyField(Availability, blank=True, related_name='taken_availabilities') And I want to filter all the availabilities that at least one Psychologist have and the same Psychologists don not have it in taken_availabilities. For example, if: psy1 has: availabilities=1am; taken_availabilities= psy2 has availabilities=2am,3am; taken_availabilities=2am This query should result in 1am, 3am (because the only psychologist that have 2am, has it taken) I could come up with this: Availability.objects.filter(psychologist__in=Psychologist.objects.filter(availabilities__id=F('id')).exclude(taken_availabilities__id=F('id'))) But it doesn't work, it shows all the Availabilities the psychologist have, doesn't matter if the only psychologists that have it have it taken. Any help with this? -
Django - Creating new User object via the Admin gives unexpected errors even if form is filled
Hey there I am trying to add a new user from Django's admin panel. From the screenshot below, you can see that even though I have correctly filled in each form input, errors are still raised by Django. I am wondering what the causes for this may be? If anyone could suggest how I'd find the solution to this problem then that'd be amazing... Quick side question is how to get the password as a password input? Code below: admin.py... from .models import UserModel, UserProfileModel from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField class UserCreationForm(forms.ModelForm): password = forms.CharField(label='Password',widget=forms.PasswordInput) passwordrepeat = forms.CharField(label='Confirm Password',widget=forms.PasswordInput) class Meta: model = UserModel fields = ('email',) def clean_password(self): # Check that the two password entries match password = self.cleaned_data.get('password') passwordrepeat = self.cleaned_data.get('passwordrepeat') if password and passwordrepeat and password != passwordrepeat: raise forms.ValidationError("Passwords do not match") return passwordrepeat def save(self, commit=True): # Save the provided password in hashed format user = super(UserCreationForm, self).save(commit=False) user.set_password(self.clean_password['password']) if commit: user.save() return user class UserUpdateForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = UserModel fields = ('email','password','is_active','is_admin') def clean_password(self): # Regardless of what the user provides, return the … -
why am i getting a tox import error before the dependencies are installed
in my django project, I have a an init.py file that imports celery, I suspect this may be causing tox to complain. /testproj/testproj/ ____init___.py from .celery import app as celery_app when I run tox, the tests successfully run, but I see this error. File "/dir/work/testproj/testproj/celery.py", line 2, in <module> from celery import Celery ImportError: cannot import name Celery mobilereports installed: amqp==1.4.9,anyjson==0.3.3,appdirs==1.4.0,Babel==2.3.4,billiard==3.3.0.23,cached-property==1.3.0,celery==3.1.24 What I find strange is that the import error is above the actual imports where celery gets imported. Why am I getting this error? celery is in my requirements.txt which is being installed by tox as you can see above, so why would i get an import error before the deps actually get installed? tox.ini [tox] envlist = mobilereports skipsdist = True [env] commands = ./runtests.sh setenv = DJANGO_SETTINGS_MODULE=testproj.settings PYTHONPATH={toxinidir} [base] deps = -r{toxinidir}/requirements.txt [env:testproj] basepython = python3 deps = {[base]deps} -
BooleanField not showing the selected value on Update
In a model I have defined the following field: manager = models.BooleanField(choices=BOOL_TYPE_CHOICES, default=BOOL_TYPE_NO) In forms: 'manager': RadioSelectWidget(choices=BOOL_TYPE_CHOICES) In widget: class RadioSelectWidget(forms.RadioSelect): template_name = 'widgets/radio-select.html' I use a custom widget just to add some classes to the Django html. The problem is not the widget, because I use the same widget in combination with SmallInteger an there are no issues. But with Boolean, one update, no option is selected, on create is ok, the default one is selected. -
Celery Tasks on Django Models
I'm trying to learn how to use celery to check a date every day on one of my models. One of my models holds an expiration date and a boolean field that says whether their insurance is expired or not. The model is pretty big so I'm going to post a condensed version. I think I have two options. Either run a celery task on the model method or rewrite the function in my tasks.py. Then I need to use Celery beat to run the schedule to check daily. I've got the function to work, but I'm passing in the model objects directly which I think is wrong. I'm also having trouble on how to use the args in the celery beat scheduler inside of my celery.py. I'm really close to getting this to work, but I think I'm going about executing a task in the wrong way. and I think executing a task on the model method might be the cleanest, I'm just not sure how to accomplish that. models.py class CarrierCompany(models.Model): name = models.CharField(max_length=255, unique=True) insurance_expiration = models.DateTimeField(null=True) insurance_active = models.BooleanField() def insurance_expiration_check(self): if self.insurance_expiration > datetime.today().date(): self.insurance_active = True self.save() print("Insurance Active") else: self.insurance_active = False self.save() … -
How to deploy Django on IIS with git hooks using virtenv on a remote Windows server?
I successfully installed and setup Django (2.0.2) using Python 3.6.4 on IIS on a remote Windows Server 2012 R2 (in a VPN environment) accordingly to this instruction: http://blog.mattwoodward.com/2016/07/running-django-application-on-windows.html I'm using SQL Server as backend and I stored the sensitive data such as the DJANGO_SECRET_KEY, DATABASE_PASSWORD etc. as environment variables in the FastCGI Settings at the IIS (see the above link, section Configure FastCGI in IIS step 14) At this point I asked me, how to deploy my apps and do all the necessary setps like install packages from requirements.txt, collectstatic, makemigrations etc. With googleing I found a possible solution using git hooks, especially a post-receive hook accordingly to this post: https://dylanwooters.wordpress.com/2015/02/21/one-command-deployments-to-iis-using-git/ So I successfully setup Bonobo Git Server on the same IIS accordingly to this instruction: https://bonobogitserver.com/install/ My thought was to put all the required commands into this post-receive hook file as I would do in the development environment. I ended up with this file at location \inetpub\wwwroot\Bonobo.Git.Server\App_Data\Repositories\myapp-master\hooks\post-receive: #!/bin/sh DEPLOYDIR=/c/apps/myapp VIRTENVDIR=/c/virtualenvs/myapp GIT_WORK_TREE="$DEPLOYDIR" git checkout -f cd $VIRTENVDIR source Scripts/activate cd $DEPLOYDIR pip install -r requirements.txt python manage.py collectstatic --noinput python manage.py makemigrations python manage.py migrate I grant permission to the Scripts/activate file and I receive no erros during push from … -
getting data from one django to a template from another django app
Have Two Django Apps. Work and Blog The Blog App template folder has the index.html Here is the view.py from work from django.shortcuts import render from . import models from work.models import Work from blog import views # Create your views here. def work(request): template_name = "blog/templates/index.html" work_list = Work.objects.all context={'work_list':work_list} return render(request,template_name,context) I want it to be shown in index.html which is in the blog app <div class="work"> <section id = "work-list"> <div class="container"> <div class = "row"> {% for works in work_list %} <div class="col-md-4"> <div class="lol"> <img class="img-rounded img-responsive" src = "{{works.image}}" alt=""> </div> </div> {%endfor%} </div> </div> </section> </div> index.html is in the blog app This is the directory blog template index.html models.py views.py Work views.py models.py -
Django templates links broken
I have two pages that use base.html as a base template: index.html and login.html. login.html has a fully functional nav bar (links and :hover working) where index.html shows the nav bar but won't recognise the links. Bear with me as this is my first post, so I have no idea what I need to provide etc... base.html: <!DOCTYPE html> <html> <head> <title>{% block title %}Graduate Proofreading | Professional Essay Proofreading{% endblock title %}</title> {% block head_meta %} {% block head_meta_charset %} <meta charset="UTF-8"> {% endblock head_meta_charset %} {% block head_meta_contentlanguage %} <meta http-equiv="Content-Language" value="en-UK" /> {% endblock head_meta_contentlanguage %} {% block head_meta_viewport %} <meta name="viewport" content="width=device-width, initial- scale=1"> {% endblock head_meta_viewport %} {% endblock head_meta %} {% block head_css %} {% block head_css_site %} <!--=================================CSS LINKS==========================================--> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="https://www.w3schools.com/lib/w3-theme-cyan.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"> <script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script> <!-- Custom fonts for this template--> <!-- Custom styles for this template--> {% endblock head_css_site %} {% block head_css_section %} <style type="text/css"> </style> {% endblock head_css_section %} {% block head_css_page %} {% endblock head_css_page %} {% endblock head_css %} </head> <body> <!-- Hidden Side Navigation --> <nav class="w3-sidebar w3-bar-block w3-card w3-animate-left w3- center " style="display:none" id="mySidebar"> <h1 class="w3-xxxlarge w3-text-theme">Side Navigation</h1> <a href="#" … -
Django Login Incorrect password showing for correct password
I am making a login form and using Django 1.8 Python 3.5 But I am getting Incorrect password for valid username and password what should I do ? I have made a simple login form but am not able to figure out the error , please help This is my login/forms.py from django import forms from mainpage.models import User from django.contrib.auth import ( authenticate, login, logout, get_user_model, ) class UserLoginForm(forms.Form): username=forms.CharField(max_length=40) password=forms.CharField(max_length=40,widget=forms.PasswordInput) def clean(self,*args,**kwargs): username=self.cleaned_data.get("username") password=self.cleaned_data.get("password") user_qs = User.objects.filter(username=username) if user_qs.count() == 0: raise forms.ValidationError("The user does not exist") else: if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("Incorrect password") if not user.is_active: raise forms.ValidationError("This user is no longer active") return super(UserLoginForm,self).clean(*args,**kwargs) This is my login/views.py def login_view(request): form1=UserLoginForm(request.POST or None) print(request.user.is_authenticated()) if form1.is_valid(): username=form1.cleaned_data.get("username") password=form1.cleaned_data.get("password") user=authenticate(username=username,password=password) auth_loginwa(request,user) if(request.user.is_authenticated()): return redirect("home2") context= { "form1": form1, } return render(request, "login.html",context) This is my mainpage/models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) -
Working with ManyToManyField
How to get a choice from one to several Executors (owner) from the group "Technical support", in the selection field in the application in the admin panel. Now I can only configure to receive one, and no more, performers. Used ForeignKey: class Application(models.Model): ... owner = models.ForeignKey(User, null = True, blank = True, limit_choices_to={ 'groups__name': 'Техническая поддержка'}) After reading, I realized that i can get them through ManyToManyField, and did the following: class Owner(models.Model): executor = models.ForeignKey(User, null = True, blank = True, limit_choices_to={ 'groups__name': 'Техническая поддержка'}) class Application(models.Model): ... owner = models.ManyToManyField(Owner, verbose_name = 'Исполнитель') But, the performer is taken not from the group "Technical support", but from the "executor", which still needs to be created. And even if to create, the choice will be as follows: enter image description here In general, I just can not figure it out. Many thanks to all those who try to help with this problem.