Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Insert logged username in database with Django Form
I'm developping my Django web application and I would like to insert usernames field in my table when any users are adding a row in the database. Obviously, users have to be logged in my application. My form.py file looks like this : class CustomLabelModelChoiceField(forms.ModelChoiceField): def __init__(self, *args, **kwargs): self._label_from_instance = kwargs.pop('label_func', force_text) super(CustomLabelModelChoiceField, self).__init__(*args, **kwargs) def label_from_instance(self, obj): return self._label_from_instance(obj) class BirthCertificateForm(forms.ModelForm): fk_parent1 = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Père", label_func=lambda obj: '%s %s %s' % (obj.lastname, obj.firstname, obj.social_number)) fk_parent2 = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Mère", label_func=lambda obj: '%s %s %s' % (obj.lastname, obj.firstname, obj.social_number)) mairie = forms.CharField(widget=forms.HiddenInput(), initial=Mairie.objects.using('default').last().city.encode('utf-8')) user = forms.CharField(widget=forms.HiddenInput(), initial=user.username) social_number = forms.CharField(widget=forms.HiddenInput(),required=False) class Meta : model = BirthCertificate fields = ['lastname', 'firstname', 'sex', 'birthday', 'birthhour', 'birthcity', 'birthcountry','fk_parent1', 'fk_parent2', 'mairie', 'user', 'social_number'] widgets = {'country': CountrySelectWidget()} def __init__(self, *args, **kwargs): super(BirthCertificateForm, self).__init__(*args, **kwargs) for key, value in self.fields.iteritems() : self.fields[key].widget.attrs.update({'class':'form-fields'}) How I can write this line : user = forms.CharField(widget=forms.HiddenInput(), initial=user.username) In order to know which user has added, modified or deleted row(s) ? user.username works in my html template as example, but I don't know How I can pick up this variable and put it directly in my form ? Thank you by advance ! -
Django deferred jsonfield fetching
I use defer on my querysets. And then sometimes I need to directly fetch deferred field. In Django 1.6.5 everything was alright. But then I made upgrade to Django 1.10.5. And now when I try something like Document.objects.defer('test').test I get KeyError. Turns out it only happens with custom fields jsonfield.JSONField. 'Native' django fields are working just fine. And the error is: File "/home/serf/dogbone/venv/local/lib/python2.7/site-packages/jsonfield/subclassing.py", line 36, in __get__ return obj.__dict__[self.field.name] KeyError: 'cached_analysis' So, I have a feeling that changes in this patch `https://github.com/django/django/pull/6118 are not taken into account in jsonfield module (I use latest 2.0.1 version). I may be wrong though. I tried to use some magic, like creating CustomJSONField(jsonfield.JSONField) with overwritten __get__ method (to try to figure things out) but this method is not even called during reproduce, so I have failed miserably. -
Django get the most recent object matching a query
Let's say I have a model of the sort of: class Related(models.Model): ... stuff .... class Example(models.Model): field1 = models.ForeignKey(Related, on_delete=models.CASCADE, related_name='+') field2 = models.ForeignKey(Related, on_delete=models.CASCADE, related_name='+') created = models.DateTimeField(default=timezone.now) ... more fields What I want to do is select the latest example for each fixed pair of field1 and field2. I want to select all the fields from Example. Assume that the number of entries in Example could be in the order of millions. An example sql query that would do the job is something like (assuming an app name 'test'): select * from test_example as e where not exists ( select id from test_example as e2 where e2.field1_id = e.field1_id and e2.field2_id = e.field2_id and e2.created > e.created) Is there any way that I express something similar with the QuerySet API? So far the only solution I have found is to run raw SQL and I would really like to avoid that. -
Why won't this mistyped field name on a Django model throw an exception?
I have a model named Foo. I can create a new instance of this model, and save it to the database, even if I assign a field name that doesn't exist. For instance: foobar = Foo.objects.create() foobar.abcdefg = True # The field abcdefg does not exist! foobar.full_clean() foobar.save() Why won't Django throw an exception when assigning to a field that doesn't exist? How can I make it throw an exception, at least during full_clean? -
Django Filter on most common occurrence in many to many field
I would like to filter/exclude my query-set based on the most common occurrence (mode) of my many to many field which is a charfield: For example in my example below I would like to filter among the classes that contain classrooms with students where "David" is the most common name in the class. (Django version 1.9.2) #models.py class Student(models.Model): name = models.CharField() class Class(models.Model): name = models.CharField() students = models.ManyToManyField(Student) #views.py Class.objects.filter(students__mode = 'David') -
Haystack Elasticsearch shows no results Django
Hello I am trying to implement a Search into my (local)Site and used Haystack for it. For the Backend i choose Whoosh, which worked a bit (I got some results but not as many as i wanted) so I tried to switch to Elasticsearch instead because there is way more support and active users. I got Elasticsearch running on Port 9200 (Version 5.4.0). ./manage.py rebuild_index is working when I run ./manage.py haystack_info I get Number of handled 3 index(es). - Model: Tag by Index: <my_profile.search_indexes.TagIndex object at 0x10ff51ae0> - Model: UserProfile by Index: <my_profile.search_indexes.UserIndex object at 0x10ff51c18> - Model: Post by Index: <my_profile.search_indexes.PostIndex object at 0x10ff51db8> The Problem is Haystack is not finding any Results, no matter what I search for. It has to be something with Elasticsearch because I got results with Whoosh before. I have a search_indexes.py file and the Post_text.txt in the right folder. When I run $ curl -XGET 'http://127.0.0.1:9200/PostIndex/_mapping?pretty=1' in the Terminal he shows me an Error that the Index is not found. This appears to be a Problem with Version 5.x of Elasticsearch and it is recommended to use Version 2.x or 1.x. Does anybody know what I could do to get results? Should … -
Deploy django app to heroku with postgresql database
I have developed a sample django app using Postgresql as my db engine. My pip freeze look like this appdirs==1.4.3 Django==1.11.1 packaging==16.8 pkg-resources==0.0.0 psycopg2==2.7.1 pytz==2017.2 six==1.10.0 How can I configure my app so that it deploys the local postgesql database alog wiith it on heroku. -
When I reload solr admin .Error loading class 'solr.SortableIntField' just happend
I did the project follow the 'Django by examples',when i adding a search engine with Solr and Haystack,some wrong happend in building indexes. When i run the following command: python manage.py build_solr_schema I got the following XML <?xml version="1.0" ?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more Save the following output to 'schema.xml' and place it in your Solr configuration directory. contributor license agreements. See the NOTICE file distributed with -------------------------------------------------------------------------------------------- this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <schema name="default" version="1.5"> <types> <fieldtype name="string" class="solr.StrField" sortMissingLast="true" omitNorms="true"/> <fieldType name="boolean" class="solr.BoolField" sortMissingLast="true" omitNorms="true"/> <fieldtype name="binary" class="solr.BinaryField"/> it's not complete ,and i copy the whole XML to the solr/blog/config/schema.xml Then i … -
Access field from intermediary model in Django Rest Framework
Having a hard time trying to access a field from an intermediary model in DRF. Let's see the related models: class School(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=50, verbose_name=_(u'Name')) staff_order = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name=_(u'Staff ordering'), through='StaffOrder', related_name='school_staff_order') class User(AbstractUser): phone = models.CharField(max_length=20, blank=True, null=True) address = models.CharField(max_length=150, blank=True, null=True) about_me = models.CharField(max_length=200, blank=True, null=True) REQUIRED_FIELDS = ['email'] def __unicode__(self): return u'{0}'.format(self.username) class StaffOrder(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) school = models.ForeignKey(School) order = models.PositiveSmallIntegerField(default=0, verbose_name=_(u'Staff ordering for this school')) class Meta: verbose_name_plural = _(u'Staff ordering') Now what I'm expecting is being able to read order field from StaffOrder in when returning a QuerySet for users (StaffSerializer). Here are the Serializers: class StaffRoleSerializer(serializers.ModelSerializer): class Meta: model = StaffOrder fields = ( 'order', ) class StaffSerializer(serializers.ModelSerializer): username = serializers.CharField(max_length=75, required=True) email = serializers.CharField(max_length=75, required=True) order = StaffRoleSerializer(source='school_staff_order') class Meta: model = User What is returned in order for the StaffSerializer is a Manager, instead of the order field from the StaffOrder model related with this User. I'd love to be able to also write this value from the serializer, but I can do that in the Viewset, but I really need to read this value in the Serializer itself...any idea what I'm missing here? -
Django InlineModelAdmin “Add another” link not appear in chrome
InlineModelAdmin, for some reason, is not displaying the "Add another" link when I run the project in Chrome. I tested it in Safari and it shows up normally. I saw in the Django documentation that the display of this link depends on Javascript being enabled in the browser. I already checked and Chrome is set to allow javascript. Any idea? -
Running a .sql file after migrations in django
I have setup my migrations in django (very small project); but I have a .sql file that has a bunch of data I need in the database. What is the best way (or is it even possible) to have this .sql file executed after/during running migrations? The sql file just contains an insert of the data like so: INSERT INTO `mileages_mileages` (`id`, `miles`, `start_location`, `end_location`) VALUES (NULL,3, 'Location 1', 'Location 2'), I just need to execute that .sql file after running the initial migrations of my models. Is that possible? -
Celery throws error when connecting to RabbitMQ but tasks still get executed sometimes
After having set-up celery according to the tutorial here, I run into this error: consumer: Cannot connect to amqp://proj:**@127.0.0.1:5672/my_vhost: [Errno 111] Connection refused. Everything is configured properly, my_vhost exists, a user proj with the corresponding password is registered on it. Also, when I try to see the workers running and run this: import celery celery.current_app.control.inspect().ping() I get: error: [Errno 104] Connection reset by peer My settings: BROKER_URL = 'amqp://proj:my_pass@localhost:5672/my_vhost' The catch is that some of the tasks still run even if I get this error. -
In Django remove doublicates of a QuerySet when using parler
I have a model like this: from django.db import models from django.utils.translation import ugettext_lazy as _ from parler.models import TranslatableModel, TranslatedFields ... class UnitNode(TranslatableModel): ... translations = TranslatedFields( title=models.CharField(_(u'title'), max_length=1024), slug=models.SlugField(_('slug')) ), ) ... I want a QuerySet of UnitNodes without duplicates, sorted by slug. When I query something like this: qs = UnitNode.objects.distinct().order_by("translations__slug") I get duplicates. How do I get rid of duplicates? -
Django + Phonegap Authentication
I am building an application with Phonegap on the client side and a Django server on the backend. I am not able to authenticate the user. Here's my code. $.ajax({ url: "http://192.168.0.101/userbase/login/", type: "POST", dataType: "json", data: {"username": username, "account": account, "password": password,}, success: function (json) { if (json.logged_in == true) { window.location.href = "products.html"; } else { alert("Invalid Credentials. " + json.error); } } }); This is the AJAX call to log in the user from the index.html. It is authenticated temporarily as in the views.py # SOME CODE login(request, user=user) print(request.user.is_authenticated()) response = JsonResponse(response_data) response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Methods'] = 'OPTIONS,GET,PUT,POST,DELETE' response['Access-Control-Allow-Headers'] = 'X-Requested-With, Content-Type' return response prints True. But, when the window redirects to products.html and I make an AJAX request to my Django server and check if the user is authenticated or not, it returns False. I am not able to find the error. Please help. Thanks. -
django filter and adding
I'm in trouble with django and the model thing, have some data in a db with date, integrer and string like that : DATE number1 number2 name 2017/05/22 30 3000 'foo' 2017/05/22 20 2000 'bar' 2017/05/23 40 4000 'foo' 2017/05/23 50 5000 'bar' i want to have the sum of the integrer with the same date and get ride of the name field like : DATE number1 number2 2017/05/22 50 5000 2017/05/23 90 9000 if someone have a simple idea i'll be so happy :) for now i'm coding a range of date and filter my django object with current date but it's not very elegant. Thanks in advance :) -
Celery is repeating my tasks three times
I call some tasks in celery one time but celery executes all of them three times. Is it an expected behavior of celery or is it a misconfiguration? I'm using Django 1.5.11, Celery 3.1.23 and Redis 3.0.6. -
Change fields of ModelForm dynamically
Is it possible to change the fields in a ModelForm dynamically? I am trying to show only a small number of fields in a ModelForm when the user adds a new instance (of the Model) from the frontend but larger number of fields when the user edits an instance. The Form class looks something like this: class SchoolForm(ModelForm): class Meta: model = School #want to change the fields below dynamically depending on whether its an edit form or add form fields = ['name', 'area', 'capacity', 'num_of_teachers'] widgets = { 'area': CheckboxSelectMultiple } labels = { 'name': "Name of the School", 'num_of_teachers': "Total number of teachers", } Trying to avoid having two separate classes since that doesnt seem DRYish. I found some SO posts with the same question for the admin page where we could override get_form() function but that does not apply here. Also, this answer suggests using different classes as the normal way and using dynamic forms as an alternative. Perhaps dynamics forms is the way forward here but not sure since I also have custom init methods etc on that Class. -
Django 1.10 YAML fixtures format error (mapping values are not allowed here)
I have a django website utilising the following model: models.py from django.db import models # Create your models here. class ObjectFoo(models.Model): number_text = models.CharField(max_length=2) Here is a snippet of my YAML fixtures file: 01_foobar_fixtures.yaml model: mysite.myapp.ObjectFoobar pk: 1 fields: number_text: '1' pk: 2 fields: number_text: '2' When I run ./manage.py loaddata /path/to/01_foobar_fixures.yaml, I get the following error: django.core.serializers.base.DeserializationError: Problem installing fixture '/path/to/mysite/myapp/fixtures/01_foobar_fixtures.yaml': mapping values are not allowed here in "/path/to/mysite/myapp/fixtures/01_foobar_fixtures.yaml", line 2, column 5 It's obvious from the error message that my YAML format (which I prefer over JSON - because of brevity), is wrong. Can anyone see what's wrong with my YAML? -
Radio buttons are not showing, instead checkboxes are being displayed
This form was showing the radio-buttons when in the Function based views but changed to the checkbox when I introduced the Class based views, what could be the solution to this. I want them to be showing the radio-buttons again forms.py class ProductImagesForm(forms.ModelForm): media = forms.ImageField(label='Image') featured_image = forms.BooleanField(initial=True) def __init__ (self, *args, **kwargs): super(ProductImagesForm, self).__init__(*args, **kwargs) self.fields['featured_image'] = forms.BooleanField( widget = forms.RadioSelect(attrs={'checked': 'true'}, choices=((self.prefix, 'featured'),))) models.py def product_download(instance, filename): return '%s/%s' %(instance.product.slug, filename) class ProductImages(models.Model): product = models.ForeignKey(Product) title = models.CharField(max_length=120) media = models.ImageField(upload_to=product_download, width_field='max_width', height_field='max_height', null=True, blank=True) max_width = models.CharField(max_length=100, null=True, blank=True) max_height = models.CharField(max_length=100, null=True, blank=True) featured_image = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return unicode(self.media) class Meta: verbose_name = "product image" verbose_name_plural = "product images" -
Why doesn't this query return the get_absolute_url? But another one does
I'm trying to learn why this query renders an empty <a href="">Some project</a> in my template. Am I missing the pk? from django import template from architecture.models import Architecture register = template.Library() @register.inclusion_tag('cubo/winnings.html') def winnings(): winnings = Architecture.objects.values('year', 'project').order_by('year').filter(won=True) return {'winnings': winnings} But this query do work. @register.inclusion_tag('cubo/winnings.html') def winnings(): winnings = Architecture.objects.filter(won=True).order_by('-year') return {'winnings': winnings} the template: cubo/winnings.html <ul> {% for win in winnings|dictsortreversed:"year" %} <li> {{ win.year|date:"Y" }} - <a href="{{ win.get_absolute_url }}">{{ win.project }}</a> </li> {% endfor %} </ul> And for reference here is the models.py from autoslug.fields import AutoSlugField from django.db import models from django.urls import reverse class Architecture(models.Model): live = models.BooleanField(default=False) won = models.BooleanField(default=False) project = models.CharField(max_length=200, null=True) year = models.DateField(null=True) description = models.TextField(null=True) typology = models.ManyToManyField(Typology) slug = AutoSlugField(populate_from='project', max_length=200) def __str__(self): return self.project def get_absolute_url(self): return reverse('architecture-detail', args=[str(self.slug)]) -
Refresh django table automatically when new data is available
I have implemented fetch_results function in order to add new data to the database in a django website. This function is activated in every page refresh. views.py def fetch_results(): # global result documents = DRSDocument.objects.all() for doc in documents: computed_image_path = os.path.join(WORKING_DIRECTORY, doc.uuid, 'process_result.jpg') drs_status = doc.status if os.path.isfile(computed_image_path): if drs_status == 'Q': doc.date_process_end = timezone.now() doc.status = 'F' doc.save() When an image is available in the server os.path.isfile(computed_image_path) data is available in the django web page. HTML {% extends "retinal_drs/base_site.html" %} {% load staticfiles %} {% block head %} <script type="text/javascript"> var select_for_deletion_status = true; function selectAllForDeletion() { var inputs = document.getElementsByTagName('input'); for(var i=0;i<inputs.length;i++) { if(inputs[i].name.startsWith('delete_')){ //console.log(inputs[i]); inputs[i].checked = select_for_deletion_status; } } select_for_deletion_status = !select_for_deletion_status; return false; } </script> {% endblock %} {% block content %} <div id="container2c" align="center"> <BR> <BR> {% if drs_images %} <BR> <form method="post" action="{% url 'retinal_drs_delete_multiple' %}" style="height: 530px;overflow-y: scroll;width: 90%;"> {% csrf_token %} <table id="myTable" style="width:90%;font-style: normal;"> <thead> <tr style="font-style: italic;"> <th><div class="th-inner"><IMG title="Click to select all" width=12px src="{% static 'images/red-delete-button.png' %}" onclick="return selectAllForDeletion();"></IMG></div></th> <th><div class="th-inner">&nbsp;Image&nbsp;</div></th> <th><div class="th-inner"> DRS Status </div></th> <th><div class="th-inner"> Proc. Started </div></th> <th><div class="th-inner"> Proc. Finished </div></th> <th><div class="th-inner">&nbsp;Result&nbsp;</div></th> <th><div class="th-inner">&nbsp;Computed DRS&nbsp;</div></th> <th><div class="th-inner">&nbsp;PDF&nbsp;</div></th> <th><div class="th-inner">&nbsp;Delete&nbsp;</div></th> <th><div class="th-inner">&nbsp;#&nbsp;</div></th> </tr> … -
Django Rest Framework SlugRelatedField: field may not be null
I am using DRF for API requests. I have a serializer which is serializing several fields. Some of the fields I have is are SlugRelatedField. These fields have allow_null=True as not all requests will have all fields posted. The issue I am having is, when I have many=True the allow_null does not seem to work. I get the following error "tag":["This field may not be null."] tag = serializers.SlugRelatedField( queryset=Tag.objects.all(), many=True, required=False, allow_null=True, slug_field="name" ) Anyone able to assist? -
user account using django
So I want to know; how does user account work? Like on Facebook User account when a user logs in there will be profile page were they can update there info. I would like to add that to my web app using Django. Thanks in advance. -
Django celery tasks in separate server
We have two servers, Server A and Server B. Server A is dedicated for running django web app. Due to large number of data we decided to run the celery tasks in server B. Server A and B uses a common database. Tasks are initiated after post save in models from Server A,webapp. How to implement this idea using rabbitmq and in my django project -
Is it possible to import csv with tastypie
I am developing restful service in django using tastpie app. So far it helped me in developing all my endpoints. But now I have a requirement to upload csv to system. In the front end I mean in the django app I have UI for import csv . So basically I want to call that function once I recieved that file. Is this possible in tastypie . Is there any tutorial available