Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to compare the changes in a modelform with model (django)
I do not know how to compare if a modelform is equal to a model in django. thank you very much models.py class Person(models.Model): name = models.CharField(max_length=45) lastname = models.CharField(max_length=45) dni = models.BigIntegerField() email = models.EmailField(max_length=30) status = models.BooleanField() departament = models.ForeignKey(Departament) #char forms.py class Form_Person(forms.ModelForm): class Meta: model = models.Person fields = ['name', 'lastname', 'dni', 'address', 'phone', 'email', 'position', 'status', 'departament'] views.py @auth.decorators.login_required(login_url='login') def persons_person(request,id='id'): page_name = 'Persons' try: person = models.Person.objects.get(id=id) list_departaments = models.Departament.objects.all() list_departaments = list_departament.exclude(name = person.departament) if request.method == 'POST': form_person = forms.Form_Person(request.POST, initial='person') Here the comparison would be implemented ### code to compare ### # if form_persona.is_valid() and form_person.has_changed(): #Something like that # ***how to compare*** # form_person.save() except models.Person.DoesNotExist as e: person = None list_departaments = None return render(request, 'app/persons/person.html', {'page_name':page_name, 'person':person, 'list_departaments':list_departaments}) -
Django response nested models
I have the following models: class Asset(models.Model): isin = models.CharField(max_length=100) asset_type = models.CharField(max_length=50) last_price = models.FloatField security_weight = models.FloatField update_date = models.DateTimeField def __str__(self): return self.isin class Meta: ordering = ('isin',) class PortfolioElement(models.Model): nominal = models.FloatField weight = models.FloatField asset = models.OneToOneField( Asset, on_delete=models.CASCADE, primary_key=True, ) def __str__(self): return self.asset.isin class Meta: ordering = ('asset',) class Portfolio(models.Model): number = models.CharField(max_length=100) update_date = models.DateTimeField elements = models.ManyToManyField(PortfolioElement) def __str__(self): return self.number class Meta: ordering = ('number',) class Client(models.Model): number = models.CharField(max_length=100) update_date = models.DateTimeField portfolios = models.ManyToManyField(Portfolio) def __str__(self): return self.number class Meta: ordering = ('number',) and the following serializer: class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = ('number', 'portfolios') depth = 1 However, I would like to see the actual data in the portfolios (and portfolio elements). But when I try to make a GET request on an arbitrary Client (by the (Client).number field) I can only see the following: { "number": "28101317", "portfolios": [ { "id": 14, "number": "5471-339425", "elements": [ { "asset": 326 }, { "asset": 327 }, ... (and so on) How can a tweak my code, so that I also can get the actual "asset" information? /Niclas -
Travis Ci gives: ProgrammingError: type "jsonb" does not exist
So ./manage.py test runs correctly on my local machine but it doesn't on travis. i get this error django.db.utils.ProgrammingError: type "jsonb" does not exist which has something to do with not having the right database ? but im using postgresql as I've stated in the settings.py and .travis.yml ? Does anyone have a clue why i might be getting this error. .travis.yml language: python python: - '2.7' services: postgresql before_install: - export DJANGO_SETTINGS_MODULE=BunqWebApp.settings - export PYTHONPATH=$HOME/builds/OGKevin/ComBunqWebApp install: pip install -r requirements.txt before_script: - psql -c "CREATE DATABASE travisci;" -U postgres - ./manage.py migrate script: - ./manage.py test settings.py if 'TRAVIS' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'travisci', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', } } requirements.txt Django==1.10.6 gunicorn==19.7.1 psycopg2==2.7.1 requests==2.10.0 whitenoise==3.3.0 dj-database-url==0.4.1 -
Where has cleaned_data vanished in Django 1.11?
I have created an inlineformset_factory as below : formset = inlineformset_factory(Author, Book, form=BookForm, formset=BaseBookFormSet, can_order=False, can_delete=True, extra=1, fields=('id', name) ) BookForm is as below: class BookForm(forms.ModelForm): name = forms.Charfield(required=True) def __init__(self, *args, **kwargs): super(BookForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Div( Field("id", type="hidden"), Field("name"), Field("DELETE") ) ) class Meta: model = Book fields = ('id', 'name') def clean_name(self): book_name = self.cleaned_data['name'] try: book = Book.objects.get(name=book_name) return book except: return book_name def clean(self): cleaned_data = super(BookForm, self).clean() ... other operations on cleaned_data ... def has_changed(self): changed = super(StockForm, self).has_changed() cleaned_data = self.clean() ... other code here ... This is throwing an error on submitting the form : Exception Type: AttributeError Exception Value: 'BookForm' object has no attribute 'cleaned_data' when formset.is_valid() is called in views.py. Traceback first shows the line in has_changed where the self.clean is being called, and then the line in clean() where the super clean is being called. This used to work fine in django 1.10. When I tried printing dir(self) in Django 1.10 it does show 'cleaned_data' as one of the attributes where as in Django 1.11 it does not. Where has the 'cleaned_data' vanished in Django 1.11? -
How do install node.js and bower in virtualenv
I'm trying to see how django-scheduler works and so want to install it in a virtualenv. Having unzipped the files into the relevant directory, here's what I've done: virtualenv env env/bin/pip install -r requirements.txt export DJANGO_SETTINGS_MODULE=project_sample.settings python manage.py bower install At this point I get the error: /usr/bin/env: βnodeβ: No such file or directory Given that didn't work I've tried following this blog and did env/bin/pip install nodeenv env/bin/pip install django-bower env/bin/nodeenv --prebuilt -p I get the same result. How do I install within a virtualenv? -
Django csv HttpResponse working locally broken in production
I have a django view which allows users export a csv based on a date selection. Locally this feature works fine. I have the web app hosted on Azure. In Azure I'm getting a 404 (not found) error on the csv response URL. My guess is I'll need to change something in settings.py for production or in Azure to allow the csv download. The view code: if 'emp-csv' in request.GET: # data from date selection data = request.GET['data'] # Convert string to list cleandata = ast.literal_eval(data) # creating csv response response = HttpResponse(content_type="text/csv") response['Content-Disposition'] = "attachment; filename='hours_report.csv'" # Write data to csv file and return fieldnames = ['Supervisor', 'EmployeeID', 'FirstName', 'LastName', 'NT', 'OT', 'OT2', 'Project', 'Client', 'date'] writer = csv.DictWriter(response, fieldnames=fieldnames, dialect='excel', ) writer.writeheader() writer.writerows(cleandata) return response The URL code: url(r'employees/report/export', hours_views.report, name="export_csv"), The URL generated in Azure: https://xyzxyz.azurewebsites.net/employees/report/export?csrfmiddlewaretoken=(..CSRF_TOKEN)&data=(...DATA) -
How to write Django REST Api without model to send a file using Requests
I want to write a rest method without model so that I can send a pdf file using python requests module. This csv file should be remotely accessed from the server. for example - I have logged in to my project using requests and get the cookies and headers so that I can pass it to the following requests method.. files = {'file': open('test.pdf', 'rb')} response = requests.post(url, files=files, headers=api_headers, cookies=api_cookies) so this url should be : which will be for that rest method. Can anyone please help me on how to write this rest method? -
Error while opening django shell - ImportError: No module named request
I get the following error when I try to open django shell. python manage.py shell Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/VirtualEnv/ChatterBox/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/VirtualEnv/ChatterBox/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/usr/local/VirtualEnv/ChatterBox/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/VirtualEnv/ChatterBox/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/VirtualEnv/ChatterBox/lib/python2.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named request -
reading and writing configuration file .ini usind django framework
I am new in python framework. I want to know how reading configuration file then fill a HTML form of this informations then editing later. what i do in views and templates??? Best Regards. -
File uploading in django
form method="post" enctype="multipart/form-data">{% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> {% if uploaded_file_url %} File uploaded at: {{ uploaded_file_url }} {% endif %} But how do i add a file and save it in media directory of application in django project? -
Django queryset after update() call?
after updating queryset, queryset.update(quantity=F('quantity') + increment_amount) serializer = MySerializer(queryset, many=True, context={'product': product}) serializer.data # here sometimes wrong old data queryset.values() # shows correct data. If I evaluate queryset (in DRF), would it contain the update I made above? My teammate found sometimes DRF serialized data doesn't have the updated info. But queryset.values() shows the correct updated info. I can't reproduce this, and are having hard time to google. -
how can i use two functions of the same name in model django
i have two functions in the same model , and i need to use them in my generic view , one function in a view and the other function in the other view . class Container(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE ,null=True) . . state = models.CharField(max_length = 120) Free_volume = models.FloatField() def get_absolute_url(self):#the first function return reverse('vehicule_app:container-view') def get_absolute_url(self):#the secont function return reverse('vehicule_app:details', kwargs={'pk' : self.pk}) i want to use the first function in this view : form_class = ContainerForm template_name = 'vehicule_app/container_form.html' and i want to use the second function in other view : class ContainerCreate(CreateView): form_class = ContainerForm template_name = 'vehicule_app/container_form.html' -
Creating Custom Forms in the Django Admin Interface with Parler
I have a django 1.8 instance (and python 2) and I am using django-parler for translation. I want to customize the admin interface (I want to use django-autocomplete-light, but that's not relevant). But customizing the admin interface with parler seems a bit more tricky then I thought. Here is a reduced example. models.py from django.db import models from parler.models import TranslatableModel, TranslatedFields class Fruits(TranslatableModel): translations = TranslatedFields( fname=models.CharField(max_length=200) ) def __unicode__(self): return self.fname forms.py from dal import autocomplete from django import forms from .models import Fruits class FruitsForm(forms.ModelForm): class Meta: model = Fruits fields = ( 'fruits', ) admin.py from django.contrib import admin from parler.admin import TranslatableAdmin from .forms import FruitsForm from .models import Fruits class FruitsAdmin(TranslatableAdmin): form = FruitsForm model = Fruits admin.site.register(Fruits, FruitsAdmin) The Problem django.core.exceptions.FieldError: Unknown field(s) (fruits) specified for Fruits What can I do? -
Create non editable attribute for object in django
I'm currently trying to develop an app in django 1.10. I would like to know how I can initialize the attributes of an object in a one to many relationship at creation. Let's call the two related objects 'Set' (one) and 'Element' (many). The attribute 'name' of the object 'Set' is depending on the date and the number of other objects of the same kind already created. In this case I had no problem in initializing the values to the value I was interested in. However the attribute 'name' of the object 'Element' is depending on the number of other Elements created but also the 'name' of the 'Set' it is linked to. How can I obtain this information? I tried creating a method using as variable the ForeignKey value, but I was only obtaining an error in return. I tried something like: // in models.py def get_element_name(set_id): set = Set.objects.get(pk=sample_set_id) set_name = set.name return set_name +'other stuff' class Set(models.Model): // set attributes class Element(models.Model): set = models.ForeignKey(Set, on_delete=models.CASCADE) name = models.CharField(max_length=250, editable=False, default=get_element_name(set.pk)) I can see how this is wrong (the ForeignKey has no pk attribute), but I couldn't find any other solution to my problem. -
What to log in Django. Every significant user interaction?
Should I be logging every significant* user interaction with our Django app? I guess we could reconstruct interactions via regular Django log files (eg those recording errors, access etc), but perhaps having explicit records is wiser. Is it overkill to save such explicit records in the DB with reference to the User id? As opposed to using general log files. Thanks, Andy. *anything that involves money and the services people have paid for. -
Django ignores transactions
I am trying to use transaction in Django. It seems that django ignores it. All my tables are InnoDB. Transactions in mysql-shell work perfectly. python 2.7.5+, mysql 5.5.54, django 1.8.7. This is my test code: Django settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db', 'USER': ROOT_USER, 'PASSWORD': ROOT_PASS, 'HOST': ROOT_HOST, 'PORT': '3306', } } code: import django import os from django.db import transaction from my_app.models import Account os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_proj.settings") django.setup() with transaction.atomic(): Account.objects.create(account_name='newacc') raise Exception('no!!!!') The account is created in DB, although there was an exception. -
ResponseError wrong number of arguments for 'zunionstore' command
Welcome friends, I'm a newbie in Python. I am building my first Django Application. Simple shop. Unfortunately I have ResponseError. When I remove the last item from the cart I receive: ResponseError at /en/cart/ wrong number of arguments for 'zunionstore' command Request Method: GET Request URL: http://127.0.0.1:8000/en/cart/ Django Version: 1.10.6 Exception Type: ResponseError Exception Value: wrong number of arguments for 'zunionstore' command Exception Location: /home/vader/env2/lib/python3.5/site-packages/redis/connection.py in read_response, line 574 I received this error traceback from the Django Shell: Internal Server Error: /en/cart/ Traceback (most recent call last): File "/home/vader/env2/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/home/vader/env2/lib/python3.5/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/home/vader/env2/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/vader/env2/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vader/myshop/cart/views.py", line 40, in cart_detail recommended_products = r.suggest_products_for(cart_products, max_results=4) File "/home/vader/myshop/shop/recommender.py", line 40, in suggest_products_for r.zunionstore(tmp_key, keys) File "/home/vader/env2/lib/python3.5/site-packages/redis/client.py", line 1780, in zunionstore return self._zaggregate('ZUNIONSTORE', dest, keys, aggregate) File "/home/vader/env2/lib/python3.5/site-packages/redis/client.py", line 1795, in _zaggregate return self.execute_command(*pieces) File "/home/vader/env2/lib/python3.5/site-packages/redis/client.py", line 565, in execute_command return self.parse_response(connection, command_name, **options) File "/home/vader/env2/lib/python3.5/site-packages/redis/client.py", line 577, in parse_response response = connection.read_response() File "/home/vader/env2/lib/python3.5/site-packages/redis/connection.py", line 574, in read_response raise response redis.exceptions.ResponseError: wrong number of arguments for 'zunionstore' command [06/Apr/2017 20:08:29] β¦ -
Django 1.10.7 admin raw_id_fields doesnt return back id when choosing an entry from pop up
So i have the following code : class PartnerCouponGroupAdmin(admin.ModelAdmin): list_display = ['name'] raw_id_fields = ("plan","partner") search_fields = ['partner__name','name'] but when i open the admin i can see the expected magnifying glass and on clicking that it opens the pop up of that Related Field. But here is the issue, when i choose a value from that pop up, in Django 1.7.4 it used to return me back the id. But in 1.10.7 it is not returning me back an id it is instead going into that chosen row's change field. Please help me. Thank You -
Python: Django Requests
I am hosting Ubuntu on VMware Player, and I am working with Django using eclipse neon,Pydev, Anaconda3, it worked fine the request/response on the same machine(Ubuntu), but when sending a request from my windows to the hosted machine the following happens: - Request sent successfully. - No Response received. Here is my code: On Ubuntu: -Django Code: @api_view(['GET', 'POST']) def PredictLocations(request): if request.method == 'GET': locations = Locations.objects.all() serilaizer = LocationSerializers(locations, many=True) return Response(serilaizer.data) elif request.method == 'POST': serializer = LocationSerializers(data=request.data) if serializer.is_valid(): return HttpResponse('Hey') return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -Post Request: import requests,json url = 'http://localhost:8000/locations/' payload = {"X": 1.0, "Y": 0.0, "Z": 10.0, "isSafe": 2} headers = {'content-type': 'application/json'} r = requests.post(url, data=json.dumps(payload), headers=headers) print(r.status_code, r.reason, r.text) On Windows: import requests,json url = 'http://UbuntuIp:8000/locations/' payload = {"X": 1.0, "Y": 0.0, "Z": 10.0, "isSafe": 2} headers = {'content-type': 'application/json'} r = requests.post(url, data=json.dumps(payload), headers=headers) print(r.status_code, r.reason, r.text) What do you think the problem is? -
AJAX GET request to a different URL appends original URL with GET query
After making an AJAX GET request to a different URL, the original URL from which the call was made is also appended with GET query. With the below code, an AJAX request with data='a' is successfully made to the url localhost:8000/ajax/search?query=a Below is my AJAX request code: $.ajax({ type: "GET", url: "/ajax/search", data: {query: data}, dataType: "json", success: function (a) { console.log(a); } }); But, after a JsonResponse is successfully received(I have confirmed), the URL of the original page from which AJAX request was made is appended with GET data. How do I prevent the get request being appended to original URL? Here is the log data from the Django server: "GET /username/ HTTP/1.1" 200 2947 "GET /ajax/search?query=a HTTP/1.1" 200 96 "GET /username/?query=a HTTP/1.1" 200 2947 I want my URL after AJAX response to be /username/ -
Multiple settings file prevent me from running server (and executing other commands)
Django 1.11 PyCharm Community Edition 2017.1 I have created a virtualenv and activated it. Then I installed Django. And organized multiple settings files in accordance with "Two Scoops of Django". (photoarchive) michael@ThinkPad:~/workspace/photoarchive_project$ tree -I '__pycache__' . βββ docs β βββ readme.txt βββ photoarchive βββ config β βββ __init__.py β βββ settings β β βββ base.py β β βββ __init__.py β β βββ local.py β β βββ production.py β β βββ secrets.json β β βββ utils.py β βββ urls.py β βββ wsgi.py βββ home β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ __init__.py β βββ models.py β βββ tests.py β βββ views.py βββ __init__.py βββ manage.py βββ static β βββ dist β βββ css β β βββ bootstrap.css β β βββ bootstrap.css.map β β βββ bootstrap.min.css β β βββ bootstrap.min.css.map β β βββ bootstrap-theme.css β β βββ bootstrap-theme.css.map β β βββ bootstrap-theme.min.css β β βββ bootstrap-theme.min.css.map β β βββ ie10-viewport-bug-workaround.css β β βββ main.css β βββ fonts β β βββ glyphicons-halflings-regular.eot β β βββ glyphicons-halflings-regular.svg β β βββ glyphicons-halflings-regular.ttf β β βββ glyphicons-halflings-regular.woff β β βββ glyphicons-halflings-regular.woff2 β βββ js β βββ bootstrap.js β βββ bootstrap.min.js β βββ html5shiv.min.js β βββ ie10-viewport-bug-workaround.js β βββ β¦ -
Django: ImportError: No module named 'services'
I have following project setup. myproject/ manage.py requirement.txt myproject/ __init__.py settings.py urls.py services/ __init__.py models.py views.py urls.py management/ commands/ __init__.py myscript.py In myscript.py file I want to import models from services app. I have added following line. from services.models import TwitterRawFeeds, TwitterUserDetails, MarkedTweets But I am getting error ImportError: No module named 'services' I tried relative import as well.. from .models import TwitterRawFeeds, TwitterUserDetails, MarkedTweets this time i get error like Parent module '' not loaded, cannot perform relative import What i am missing here, need help. -
Django: flexible users for services and units
Alo, I am doing a small app that requires a somehow different user tool. The thing is this: I have a repair application. In the company, people can repair their fridge, washing machine and kitchen items (like blender etc). There are different technicians for each (specialized). All customer comes thru one reception but each unit (dept of fridge repair for e.g.) also have a receptionist. Then there are finance and administration units. So, I was wondering how i would go create a user who is a technician of fridge? When he logs in, i wanna take him to the technician's area so he can see repair related tasks. And for the finance department, to log in but then go to finance section of the project. I have created tables for services provided (fridge etc) and the departments (finance). How do I attach the users to each? I have seen a post that describes adding fields to the user profile but i failed to attach it to my needs. How do you guys go doing something like this? -
Django Error while rendering template IndexError
I just deployed my Django application with nginx and gunicorn, everything is running fine with every model, but for a model admin template is giving an error while rendering template. I have pasted Trace-back below. -
Django Custom User
This sounds like a million other similar questions that have been asked but bear with me. New to Django but not to Python. I followed thenewboston's tutorial on youtube so I have a general understanding of how the framework works. As a learning exercise, I want to create a "social network" type site where a user can register for a profile, filling in the following fields: -Profile pic (file) -Bio + personal info -List with add functionality, meaning the user can press a "+" and add new things to the list. The final, full length list is what I want to store. -Random file upload field. How do I go about extending the base user class? I'd prefer to do it from scratch as a learning exercise, but welcome the idea of using all-auth if there is a good guide. Rather than closing the question as a duplicate, would you mind pointing me to the best guides for a beginner in order to do this apart from the official Django documentation? Links to other threads would be ok too. There is a lot of info on the web for this and several pages use parts of the framework without any β¦