Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ForeignKey Works for Filter but not List Display
I am trying to list a ForeignKey value in Admin list_display. I am trying the solution below which seems to be the solution everyone uses, but I just get an error 'NoneType' object has no attribute 'first_name' Have I listed this correctly? Thank you. Plaque 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) ... Model Admin class PlaqueAdmin(admin.ModelAdmin): list_display = ['id', 'get_veteran', 'last_name', 'first_name', 'branch', 'group', 'draft'] def get_veteran(self, obj): return obj.veteran.first_name get_veteran.short_description = 'Veteran' ... -
Cannot start apache after editing the config httpd file for wsgi
I'm trying to deploy my homepage. I used pip install mod_wsgi to get the wsgi. And what I understood is that I only have to change the httpd file with the following: WSGIScriptAlias / /home/rasmus/MainSite/src/MainSite/wsgi.py WSGIPythonPath /home/rasmus/MainSite/src/MainSite <Directory /home/rasmus/MainSite/src/MainSite> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> I copied the directory below and pasted it into Users/rasmus/ - And I read somewhere that the home directory was found by %USERPROFILE%which opens Users directory When I try to start my apache server from services.msc I get the following error message: It runs if I remove it. So the apache server should be working, and I guess it's my configuration for deployment in httpd config that that is wrong. I use apache 2.4.25, Python 3.5.1 64-bit -
How do i update list in ListModelMixin?
I am using django rest framework to build out the backend. I have defined my model class TV(models.Model): brand = models.CharField(max_length=100, null=True) price = models.DecimalField(max_digits=10, decimal_places=2) and i have defined my view class TVViewSet(viewsets.ModelViewSet, ListModelMixin): serializer_class = TVSerializer filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter,) filter_class = TVFilter ordering_fields = ["num_stores","stores__price",] ordering = ("-num_stores",) def get_queryset(self): queryset = TV.objects.annotate(num_stores=Count('stores')).order_by('-num_stores') if self.request.GET.get("search"): selection = self.request.GET.get("search") if selection: queryset = TV.objects.annotate( similarity=TrigramSimilarity('brand', selection) ).filter(similarity__gt=0.3).order_by('-similarity') return queryset def list(self, request, *args, **kwargs): response = super(TVViewSet, self).list(request, args, kwargs) tvs = self.get_queryset().values('brands', 'stores__store') brandss = set([]) prices = set([]) for item in tvs: brands.add(item['brand']) prices.add(item['store__price']) filters = OrderedDict() filters['min_price'] = min(prices) filters['max_price'] = max(prices) filters['brand'] = brands return response Also i have defined TV Filter and TV Serializer, dont post it to no be more verbose. When i make a request to the api like this http://myapi/tv/?search=brand_name The list of possibles values that are rendered at the end of json coincide with the queryset of Tv objects obtained. But if i make a request like this http://myapi/tv/?search=brand_name&min_price=1000 Filters possibles values and Tv Objects are not coincide. Is there any way to obtain the queryset after apply a django backend filter or rest Filterset? My main goal of … -
Try to join a OneToOne relationship in Django
I need some help doing a join using Django, which seems like it should be easy. I have looked at the documentation but it seems like it won't join for some reason. I am trying to get in my view, the model.Photo and model.PhotoExtended with both joined and then displayed in the view. Currently I am just trying to get the model.Photo displayed but with a join which finds the request.user and filters it based on that. They are in different apps. models.py for model.Photo class Photo(ImageModel): title = models.CharField(_('title'), max_length=60, unique=True) slug = models.SlugField(_('slug'), unique=True, help_text=_('A "slug" is a unique URL-friendly title for an object.')) models.py for model.PhotoExtended class PhotoExtended(models.Model): Photo = models.OneToOneField(Photo, related_name='extended', help_text='Photo required', null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, help_text='User that uploaded the photo') views.py class PhotoExtendedUserView(ListView): template_name = 'photo_user_list.html' def get_queryset(self): user = get_object_or_404(User, username=self.request.user) return Photo.objects.filter(photoextended__user=user) -
How to exchange data between apps in Django using the database?
I'm using Django to work on a web. I have created 2 apps: One for the clients to register, and add their data to the database, and a second app for users to access and see the interactive interface. The idea is to use the second app to get data from the clients in the database, and use it to show some information to the user. My problem is that i don't understand how to make the second app to get the information from the database. Do i need to create the same models from the first app on model.py on the second one? Or how do i make the second app to use a Queryset to retrieve data from the database? -
Get current logged in User and set as default user on Model | Django + Python3
I'm learning about Django, and challenged myself to create an small Ticket System as study case. Got some things done, but now i'm with a little problem. How to when i save an "Ticket", Django get current logged in user and set as default on "usuario" field from my Ticket model? This is my models.py file: from django.contrib.auth.models import User from django.db import models from datetime import datetime class Projeto(models.Model): """ Classe que gere os Projetos Permite que se cadastre N usuários por Projeto Retorna: NOME_DO_PROJETO | SITE_DO_PROJETO """ nome = models.CharField(max_length=100) site = models.CharField(max_length=200) informacoes = models.TextField(blank=True) usuarios = models.ManyToManyField(User, related_name='projetos') def __str__(self): return self.nome + " | " + self.site class Ticket(models.Model): """ Classe que gere os Tickets no sistema. Retorna: DATA HORA | TITULO DO CHAMADO """ TIPOS_TICKET = ( ('BUG', 'Bug'), ('URGENTE', 'Urgente'), ('FINANCEIRO', 'Financeiro'), ('MELHORIA', 'Melhoria') ) STATUS_TICKET = ( ('ABERTO', 'Aberto'), ('AGUARDANDO_CLIENTE', 'Aguardando Cliente'), ('EM_ANALISE', 'Em Análise'), ('FINALIZADO', 'Finalizado'), ('CANCELADO', 'Cancelado'), ) titulo = models.CharField(max_length=200) conteudo = models.TextField() tipo = models.CharField(max_length=30, choices=TIPOS_TICKET, default='BUG') status = models.CharField(max_length=30, choices=STATUS_TICKET, default='ABERTO') projeto = models.ForeignKey( Projeto, on_delete=models.CASCADE, limit_choices_to={'usuarios':1} ) usuario = models.ForeignKey( User, on_delete=models.CASCADE, null=True ) data_abertura = models.DateTimeField('Data Abertura', auto_now_add=True) data_fechamento = models.DateTimeField('Data Fechamento', blank=True, null=True) def … -
convert query obj data to datetime obj
writing a management command that deletes records more than two weeks old. each model instance has a ‘confirmed_placed’ which I’m using as the comparison date. (‘confirm_placed’ is a CharField because it’s generated dynamically in a predetermined format). If my Item model looks like: class HotItem(models.Model): item_no = models.CharField(max_length=30, unique=True, blank=False, null=False) ad_date = models.CharField(max_length=20, unique=False, blank=True, null=True, default=None) create_date = models.DateField(default=date.today) item_name = models.CharField(max_length=210, blank=True, null=True) comments = models.TextField(max_length=2000, blank=True, null=True) reply = models.TextField(max_length=2000, blank=True, null=True) confirmed_placed = models.CharField(max_length=200, blank=True, null=True, default=None) def __str__(self): return u'%s %s %s %s %s' % (self.create_date, self.item_no, self.item_name, self.confirmed_placed, self.comments) What I need is the proper way to convert my objects confirmed_placed value to a date time obj and compare against twoweeksago (as defined below.) Something like: from .models import HotItem as Item twoweeksago = datetime.datetime.now() - datetime.timedelta(weeks=2) class Command(BaseCommand): help = 'Delete hotlist items placed more than two weeks ago' def handle(self, *args, **options): **hotrecords = Item.objects.filter(datetime.datetime.strptime(confirmed_placed.replace('.','').replace(',',''),' %b %d %Y')__gt=twoweeksago)** for record in hotrecords: record.delete() self.stdout.write(self.style.SUCCESS('Successfully deleted record old records')) any ideas on the proper way to format the query? -
How to configure nginx to serve static from django running in a docker container
Nginx is currently serving my site but missing all static content. I need to figure out what I'm doing wrong with this setup. docker-compose.py 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 links: - parentserver:parentserver Django settings.py 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", ] Not sure if relevant but if I docker exec into the parentcontainer running the Django app, my static directory is located at /root/proj/proj/static. That's where all my css, images, etc. is located. -
Delete FullCalendar Event Permanently
I have been stuck on this for a couple days now. I want to delete the events from the database. My model for storing the events: class Events(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) name = models.CharField(max_length=32) start = models.CharField(max_length=32) end = models.CharField(max_length=32) description = models.TextField(blank=True) attendees = models.TextField(null=True) Of course, django automatically provides a primary key as well. So the user can add events by filling out a modal form which will trigger some ajax. $.ajax({ type:'POST', url:'createEvent/', data:{ name: name, myCheckboxes: myCheckboxes, // Simply contains the attendees start: start, end: end, description: description, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, sucess: function(data){ callback(data) } }); Then in my views.py: def createEvent(request): if request.method == "POST": members = request.POST.getlist('myCheckboxes[]') name = request.POST['name'] start = request.POST['start'] end = request.POST['end'] description = request.POST['description'] Events.objects.create( user_id=request.user.id, name=name, start=start, end=end, description=description, attendees=json.dumps(members) ) return HttpResponse('<p>Done</p>') I store the information into the database and here is how I render the event: var event={ allday:true, title: name, start: start, end:end, description: description}; event = $('#calendar').fullCalendar( 'renderEvent', event, false); And I get all these values from the modal form. Alright now heres the issue, when I try to delete the event, I need some way of extracting the correct event from the database. So … -
Openshift django migrations
All the time when i make any migration i use SSH to pull migrations files and put it manually in my local git repository. Currently using putty and openshift v2.0. After that i push it on Open-shift server, with modified models. And again go into ssh to run python manage.py makemigrations python manage.py migrate i need to clone every new migration file to keep track of migrations history. Can anybody help with own solution or how i should do this procedure? -
Installing psycopg2 in an alpine docker container
I am trying to get my django application to use PostgreSQL, however, so far no luck. I set the application to use the PostgreSQL database and linked both containers using docker-compose.yml, but I am getting the error that the module psycopg2 is missing. I installed all of the dependencies as follow: apk --update add python3-dev, postgresql-client, postgresql-dev, musl-dev and when I try to install psycopg2 using pip pip3 install psycopg2 I get the following error: Collecting psycopg2 Downloading psycopg2-2.6.2.tar.gz (376kB) Installing collected packages: psycopg2 Running setup.py install for psycopg2 building 'psycopg2._psycopg' extension gcc -Wno-unused-result -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Os -fomit-frame-pointer -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.6.2 (dt dec pq3 ext lo64)" -DPG_VERSION_HEX=0x090409 -DHAVE_LO64=1 -I/usr/include/python3.4m -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-3.4/psycopg/psycopgmodule.o -Wdeclaration-after-statement error: command 'gcc' failed with exit status 1 Complete output from command /usr/bin/python3.4 -c "import setuptools, tokenize;__file__='/tmp/pip-build-6wmwilb_/psycopg2/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-f8ye_ro8-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-3.4 creating build/lib.linux-x86_64-3.4/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/psycopg1.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-3.4/psycopg2 creating build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/test_notify.py … -
Python. Django. Change feeds of form from get_context_data in CreateView
I have an issue with my Create view. I initialise it like this: class OutputCreateView(LoginRequiredMixin, generic.CreateView): template_name = 'rcapp/common_create_update.html' form_class = OutputForm model = Output def get_context_data(self, **kwargs): context = super(OutputCreateView, self).get_context_data(**kwargs) # self.form_class.fields['activity_ref'].queryset = Activity.objects.filter(rc_ref=ResultsChain.objects.get(pk=self.kwargs['rc']).pk) context['is_authenticated'] = self.request.user.is_authenticated return context def form_valid(self, form): # code code code return redirect("/portal/edit/" + str(self.kwargs['rc']) + "/#outputs-table") I have a ForeignKey Field in my model and I wanted to filter options for current view. My form is set like this: class OutputForm(forms.ModelForm): class Meta: model = Output fields = ['value', 'activity_ref'] widgets = { 'value': forms.Select(choices=(#Choises here ,), attrs={"onChange":'select_changed()', 'class':'selector'}) } I need to change a queryset for the activity_ref field. You can see a commented line in get_context_data, it's where I tried to do this. But it didn't work. How can I get what I need? -
Allow django-debug-toolbar to subnet
I can see toolbar from my pc. But I want to allow to all the subnet. This is working: INTERNAL_IPS = ('10.11.11.121','127.0.0.1','localhost') Now I to allow want to 10.11.11.X I tried without success: INTERNAL_IPS = ('10.11.11.*','127.0.0.1','localhost') INTERNAL_IPS = ('10.11.11.0/24','127.0.0.1','localhost') INTERNAL_IPS = ('10.11.11.0','127.0.0.1','localhost') -
Django trigger python script through HTML button
Im trying to execute a python script by clicking a button on my html code. I want the submit button to trigger the python script and whatever is submitted in the submit box will be added to the python script Views class TestView(TemplateView): template_name = "Vote/test.html" def post(self, request, *args, **kwargs): return redirect(reverse_lazy("Vote:Test")) Test.html <form action="demo_form.asp"> Name: <input type="text" name="fullname"> <input type="submit" value="Submit"> name.py print "Hi there %s " %test.html -
Django, mod_wsgi and apache setup
I'm trying to deploy my django application. But getting confused as to how exactly I connect my django application, mod_wsgi and apache together to make it work. some of my config: I have a domain at namecheap.com. where my setup is shown in the below picture: The blacked out is my ip. Which I have checked is corrected. My apache is version 2.4.25 - win64 I installed mod_wsgi through cmd with the command pip install mod_wsgi which was successfully installed. And is of version 4.5.14. In apache config I have put Listen to 8080. I was reading through the guide at https://pypi.python.org/pypi/mod_wsgi. They say that I can verify my installation with the command mod_wsgi-express start-server. I ran the command in the C:\WINDOWS\system32 directory and it shows me: I'm not sure if I'm executing the command in the right directory. Furthermore the apache config setup also confuses me alittle. From http://modwsgi.readthedocs.io/en/develop/user-guides/quick-configuration-guide.html They say a complete configuration looks like. I have commented my inputs. <VirtualHost *:80> <--- Can I use 8080? I noticed my chrome is using 80 and apache won't start. ServerName www.myDomain.com ServerAlias myDomain.com ServerAdmin webmaster@example.com <-- I do not have an email at the domain provider. Should I leave … -
Django in an API like + reactjs. How to generate a csrf token
I did something a bit silly while developing my project: I'm using django only for the admin and the views are use as urls for my front (reactjs) for get actions. I've nothing to protect about the data itself. But the problem is that at some point I've got assets to download and this is the only time when I've to do a POST request to my django. And here is the problem. Django is waiting for a csrf token and I didn't succeed on ignoring that (I'm using base-class views). The really silly thing is that it was working until now as I was working with the django admin (which means django template -> csrf token generation). So for a standard user he won't have it... Do you have an idea how I could proceed? Should I pass by a fake django view to be sure that the user got it? (seems to be an ugly solution). Many thanks! -
cross domain at axios
I am changing jquery ajax for axios and I not getting use axios with cross domain: axios.get(myurl, { headers: { 'crossDomain': true }, }).then(res => { console.log(res); }).catch(error => { console.log('erro', error); }) My jquery code is working: $.ajax({ type: 'GET', crossDomain: true, url:myurl, success: (res) => {}, error: (fail) => {} }) Can anyone help me? -
Filtering users by scope using django-oauth-toolkit.
I'm brand new to using DRF and DOT, and have used the DRF quickstart to make a simple API, and have followed through using the DOT quickstart to use tokens to authenticate users. I am trying to extend this API so that there are two different types of users, each of which are given a scope that gives them access to certain data from the database. So my model looks like this: class Car(models.Model): title = models.CharField(max_length=50) stock = models.IntegerField() price_tier_1 = models.FloatField() price_tier_2 = models.FloatField() def __unicode__(self): return self.title If a user has scope "type_1", I want to be able to give him data which includes the "price_tier_1" field, but not the "price_tier_2" data, and visa versa, so have two serializers to do this, class TierOneCarSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Car fields = ('title', 'price_tier_1', 'stock',) class TierTwoCarSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Car fields = ('title', 'price_tier_2', 'stock',) In my view, I want to get what the user's token's authentication scope is, so that I can use the correct serializer to send them their data. I'm not sure if I'm doing this the way one is supposed to, and any help is greatly appreciated! -
Want to add a Form field in Admin along with Model fields in django
I want to add 3 fields in my Admin.py page. out of which two fields are from Model.py and one field is from form.py. But somehow when i add these fields to admin.site.register function, an error pops up saying 'userlist' is not recognizable. Below is my code : Models.py class About(models.Model): about_author = models.TextField() pic = models.FileField(upload_to = '', default = 'static/defaul.jpg') Form.py class PostAuthorDetails(forms.ModelForm): def __init__(self,*args,**kwargs): super(PostAuthorDetails,self).__init__(*args,**kwargs) self.fields['userlist'] = forms.ModelChoiceField(queryset=User.objects.all()) class Meta: model = About fields = '__all__' Admin.py class PostAuthorDetailsAdmin(admin.ModelAdmin): form = PostAuthorDetails def get_fieldsets(self,*args,**kwargs): return((None,{'fields':('about_author','pic','userlist'),}),) admin.site.register(About,PostAuthorDetailsAdmin) Please advise whats wrong with the code. -
JStree and ajax
I am trying to update my js tree using ajax data. I want to update tree only after i get all data from ajax.Kindly help. But I am getting error as " Uncaught TypeError: $(...).jstree(...) is not a function at HTMLDocument.eval (eval at (jquery.min.js:2)" My code is as follows:- <html> <head> <style> #tree { margin-top: 50px; } </style> <script type="text/javascript" src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js'</script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.3/themes/default/style.min.css" /> <script src="//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.3/jstree.min.js"> </script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> </head> <strong>Click a node</strong> <div id="tree"></div> <script> var data =[] var data = [ { "id" : "root", "parent" : "#", "text" : "Root", "state": {"opened":false} }, ] var my_dictionary = {}; var flag = false; $(document).ready(function() { var my_dictionary = {}; //var DatesNew = Date1+"|"+Date2; //my_dictionary['Dates'] = DatesNew; console.log("in len of data is...",data.length); console.log("lennnnnnnnnnnnnnnnnof data is...",data.length); $.ajax({ url: '/ajax5/', data1:my_dictionary, cache: false, success: function (data1) { //myFunction1(); console.log("in before LOOP AJAX5...",data1); printData1(data1); } }).done(function(data1){ console.log("done with ajax call"); flag = true; }); }); function printData1(data1) { console.log("in before printData1 is...",data1); var lab =["1","2","3"]; var val = [42,55,51,22]; //var data = []; for(var i=0; i<4; i++) { dataTemp=[] dataTemp=[{ "id" : "cat1", "parent" : "root", "text" : "First Branch", "state":{"closed":false} } … -
Dynamic queryset into form
I have a form to ask for a title and a list of users. My problem is that I want to display all the users in the database but exclude the current authenticated user. I have tried several options but they were not right. Could you help me? Thank you: from django import forms class FormCal(forms.Form): titulo = forms.CharField(max_length=100) usuarios = forms.ModelMultipleChoiceField(queryset=User.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False) -
Django Combining __unaccent and __search Lookups
So I am trying to use __unaccent and __search in the same model filter, but I receive an error when doing so. I am trying to make a filter using the term "Pokemon" match the term "Pokémon" (notice the "é") Game.objects.filter(title__unaccent__icontains="Pokemon") works fine, but when I use Game.objects.filter(title__unaccent__search="Pokemon), I get the following error: ProgrammingError at /autocomplete-games/ function unaccent(tsquery) does not exist LINE 1: ...ALESCE(UNACCENT("main_game"."title"), '')) @@ (UNACCENT(p... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I am using: Python 3.5 Django 1.10 PostgreSQL (unaccent extension installed) -
Delete image in Django
I have to delete image from my app. Image has to be deleted from "media" file (directory inside my project) and from database. Here is my class DeleteImage class DeleteImage(DeleteView): template_name = 'layout/delete_photo.html' model = Profile success_url = reverse_lazy('git_project:add_photo') This is HTML page {% extends 'layout/base.html' %} {% block body %} {% if allprofiles %} <ul> {% for profile in allprofiles %} <li> <img src="/{{ profile.image }}" height="75" /> <a href="{% url 'git_project:delete_photo' user.profile.id %}">Delete</a> </li> </ul> {% endfor %} {% endif %} {% endblock %} I don't know if you need models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.FileField() Can anyone help me with this? I saw all similar Questions and Answers but can't figure this issue out... :) -
OperationalError: (1054, "Unknown column 'designparameters.inside_diameter_mi' in 'field list'")
I was attempting to add fields to the database my application is running with, but it wasnt working out so i deleted them from the table, but now i am running into the OperationalError when the site interacts with the database telling me that the field i deleted is still in field list? any ideas? Here is a full traceback: File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/contrib/auth/decorators.py", line 22, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/paragoncdn/webapps/hdcportal/myproject/contracts/views.py", line 210, in contract return render(request, 'contracts/templates.html', context) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/shortcuts.py", line 67, in render template_name, context, request=request, using=using) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/template/loader.py", line 99, in render_to_string return template.render(context, request) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/template/backends/django.py", line 74, in render return self.template.render(context) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/template/base.py", line 209, in render return self._render(context) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/template/base.py", line 201, in _render return self.nodelist.render(context) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/template/base.py", line 903, in render bit = self.render_node(node, context) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/template/base.py", line 917, in render_node return node.render(context) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/template/loader_tags.py", line 135, in render return compiled_parent._render(context) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/template/base.py", line 201, in _render return self.nodelist.render(context) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/template/base.py", line 903, in render bit = self.render_node(node, context) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/template/base.py", line 917, in render_node return node.render(context) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/template/loader_tags.py", line 65, in render result = block.nodelist.render(context) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/template/base.py", line 903, in … -
django values function strange behaviors?
I have +5 hours training to explain how : Item.objects.values('type', 'state') returns a dictionary that contains only two keys. However Item.objects.values('type', 'state').annotate(nb=Count('id')) works !! How does the interpreter knows that id attribute exists if it's not returned by values function ?