Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query annotate and agregate
How in django query write this: select sum(kolvo), reason from( select count(reason) kolvo, reason from contacts group by reason) group by reason -
django: things which become unavoidable as we learn django more
Recently i was setting up a fresh Django project then i came across local_settings.py in someones .gitignore. Then i wanted to know about it. local_settings.py is used to safe gaurd settings.py during git commit. If i dig more I found the recommended way for settings is to have different files for different env and also to have a config file. Eg: https://simpleisbetterthancomplex.com/tips/2017/07/03/django-tip-20-working-with-multiple-settings-modules.html Now or later if someone has some idea of Django may have to implement config files and multiple settings file system. So thats why i feel local_settings.py may not suffice if we know more about Django. I know not everyone who learns Django want to start with separate settings.py and config file but at later stage it looks unavoidable. Similarly my Observations after using django for a while: I found few other things which become unavoidable: 1) Custom_user is unavoidable if we want email as user name. We have to again start the migration from the beginning. 2) Using pipenv is unavoidable if we want to easily shift things to production. 3) using postgresql is unavoidable if we want to do Full text search. Ofcouse sqlite also has but django easily supports postgresql. 4) Now to have different … -
Deserialising datetime double encodes date
I am trying to deserialize a datetime value: def default(o): if type(o) is datetime.date or type(o) is datetime.datetime: return o.isoformat() def get_user_join_date(user): return json.dumps( user.date_joined, sort_keys=True, indent=1, default=default ) in order to use it as a value in payload: def jwt_payload_handler(user, active_site): payload = { "id": user.id, "date": get_user_join_date(user), "username": user.username, "role": user.role } The problem is that my datetime ends up being double encoded (it has 2 double quotes) date: ""2018-09-27T12:32:17.577000+00:00"" Any idea why this might be happening and how I can solve it? -
How to generate timestamp as default value in field in Django admin
I have a CharField and I want to put epoch time as a unique number by default. class Shakf(models.Model): name = models.CharField(max_length=255, default='', null=True) id_num = models.CharField(max_length=50, default=str(int(time.time())), unique=True) when I reload page I get the same epoch time. Then I tried to put str(int(time.time())) into function.... like this: def epoch_time(): return str(int(time.time())) class Shakf(models.Model): name = models.CharField(max_length=255, default='', null=True) id_num = models.CharField(max_length=50, default=epoch_time(), unique=True) but I get the same result. When I reload page the default value in id_num field the same. Actually it is changed if I edit model.py or reload server but it doesn't when I reload admin page in browser again -
Update object value for view only
So i have an array of objects that have a role. each role has underscores for spaces. Now i know the best way in most cases would be to simply change the value in the database to the correct format but i need it to have spaces. So instead of the value to look like this: role: this_is_my_role I need it to look like this: role: this is my role but only for my view. I've tried the following but it does not work. def view_info(request): device = Device.objects for item in device: item.role = item.role.replace('_', ' ') return render(request, 'table_view.html', {'device': device}) please note, i do not want to change the actual value in the database. I only want to change the value before rendering the template. -
Django Admin Form Injects CSS Class Into App Template
I would like to make a form surface in the /admin dashboard of DjangoCMS whereby a Boolean field (i.e., a checkbox) widget injects a Bootstrap class into a template for a specific app. Note: I cannot tweak the models.py class associated with the object surfacing in the template in a way that will impact all instances of the object...only the explicit instance represented in the template. Would be ideal if I could bypass refactoring the model entirely. The form must also live in the admin.py of the associated Django app. project app models.py <--cannot tweak views.py admin.py <--everything in here forms.py <--not implemented I'd like to do something like this with the associated Django app template which manifests the frontend presentation (not the related admin template): {% if my_object_admin_form.my_attribute.value %} <span class="offset-md-1">{{ object }}</span> {% else %} <span>{{ performer }}</span> {% endif %} I can find plenty of docs on how to style the form field in the /admin dashboard, but nothing re. this particular circumstance. I suspect my admin.py form and template tag skills need some brushing up, in general, perhaps to ask the question appropriately. Hints and solution suggestions are much appreciated. The related model is actually hooked … -
Django form picklist jquery sending list to django backend
my usecase: On the frontend i have two div containers and each with a select multiple group. The user can now shuffle items from the left "list" to the right. Below that there are couple of django form fields that the user has to fill out. After submission of the form i want to do something with the data on the backend, this includes all the items the user shuffled from the left "list" into the right "list" my problem/s: I fail to find a way to submit the whole right list together with the form. What i managed is to use jquery to shuffle items from the left list into a Django CharField (using a SelectMultiple Widget), BUT the data would only reach the backend if the user, not only shuffled the items into the right list, but also selected them. test2 = forms.CharField(widget=forms.SelectMultiple(), required=False) What i want is a way to send all the items in the right list, to the Django Backend with the form submission. pick.html ... <div class="list-group"> <select multiple="multiple" id="lstBox1" class="form-control"> <option value="ajax" class="list-group-item">Ajax</option> <option value="jquery" class="list-group-item">jQuery</option> <option value="javascript" class="list-group-item">JavaScript</option> <option value="mootool" class="list-group-item">MooTools</option> <option value="prototype" class="list-group-item">Prototype</option> <option value="dojo" class="list-group-item">Dojo</option> </select> </div> ... -
Querying RelatedManager objects
I have models such as class Model1(models.Model): f1 = models.DateField(null=True, blank=True) f2 = models.CharField(max_length=100,null=True, blank=True) f3 = models.CharField(max_length=100,null=True, blank=True) class Model2(models.Model): x = models.ForeignKey(Model1) f4 = models.CharField(null=True, blank=True) f5 = models.CharField(max_length=100,null=True, blank=True) and my admin.py reads class Model2Inline(admin.TabularInline): model = Model2 search_fields = ('f5',) extra = 1 class Model1Admin(admin.ModelAdmin): list_display = ('f1', 'f2') search_fields = ['f1'] inlines = [Model2Inline] I wish to filter Model1 based on specific values of the field f4 Something like results = Model1.objects.filter(where f4 = "some_specific_value") which is intended to result a query set containing instances of Model1 in which inline Model2's will have f4 set to some_specific_value Thanks! -
Translating PostGIS query to Django QuerySet (geoDjango postgis)
I am trying to figure out how to translate a PostGIS query to GeoDjango but i have errors... This is the code: c = conn.cursor() if( timestamp == 0 ): c.execute('SELECT X(geometry) as x, Y(geometry) AS y, accuracy, altitude, speed, timestamp FROM location ORDER BY timestamp DESC LIMIT 1;') else: c.execute('SELECT X(geometry) as x, Y(geometry) AS y, accuracy, altitude, speed, timestamp FROM location ORDER BY ABS(%s - timestamp) LIMIT 1;' % timestamp) x, y, accuracy, altitude, speed, timestamp = c.fetchone() data = { "geometry": { "type": "Point", "coordinates": [x, y], }, "type": "Feature", "properties": { "accuracy": accuracy, "altitude": altitude, "speed": speed, "timestamp": timestamp, }, } return JsonResponse(data) Any suggest? Many thanks in advice -
social-auth-app-django add path from Google console to my view
In Google dev console I add those paths: http://127.0.0.1:8000/complete/google-oauth2 http://localhost:8000/complete/google-oauth2 In my pipeline, I added redirection to this URL: register-organization/ to add extra info by form when a user already created. But I receive this URL for redirection http://127.0.0.1:8000/complete/google-oauth2/register-organization/ instead http://127.0.0.1:8000/register-organization/ Why do I have this behavior? Here are my files: urls.py: path('', include('social_django.urls', namespace='social')), path('register-organization/', unregister_views.register_organization, name='register_organization') pipeline.py: def create_organization(strategy, user=None, *args, **kwargs): if user: login(strategy.request, user, backend='social_core.backends.google.GoogleOAuth2') if not user.su_user.all(): return redirect('register_organization') return redirect('index') views.py: def register_organization(request): if request.method == 'POST': form = OrganizationModelForm(request.POST) if form.is_valid(): organization = form.save() system_user, _ = SystemUser.objects.get_or_create( user=request.user, organization=organization, user_type=UserType.objects.get(title='admin') ) return redirect('index') return render(request, 'register_organization.html') -
update_or_create overwriting field objects on both instances of a foreignkey
Hello guys I am stuck with this problem. I know update_or_create is supposed to update field if they already exist but it is overwriting data field which I am creating or updating from. Example: class Branch(models.Model): name = models.CharField() ... class Office(models.Model): name = models.CharField() branch = models.ForeignKey(Branch) Say inside the branch I have branch A, branch B In Branch A I have objects that I want to use to create object for branch B or update if it already exists. How would I do that without overwriting both field on branch A and branch B. -
Django: ValueError: "The view didn't return an HttpResponse object. It returned None instead." error
that returns this error even if I think that my view is ok. I think the problem comes from the handle of Django exceptions or from a MIDDLEWARE. I did an example view and no matter what mistakes I make in my view, this always returns the same error. I use the following url: /create-alias/10/ to have access to a non existing RedirectionFile object (to raise my Http404 error). views.py: def create_alias(request, file_id): context = {} try: test = RedirectionFile.objects.get(id=file_id) except ObjectDoesNotExist: print "Ceci est une erreur." raise Http404("Ceci n'existe pas.") context['test'] = test return render(request, "cms/create_alias.html", context) Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/create-alias/10/ Django Version: 1.11.15 Python Version: 2.7.13 Installed Applications: ('modeltranslation', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'floppyforms', 'sorl.thumbnail', 'coop_html_editor', 'colorbox', 'coop_cms', 'coop_cms.apps.email_auth', 'coop_cms.apps.coop_bootstrap', 'coop_bar', 'hifu_planet.apps.cms', 'hifu_planet.apps.centers', 'hifu_planet.apps.contact', 'hifu_planet.apps.content', 'hifu_planet.apps.relation', 'hifu_planet.apps.stories', 'hifu_planet.apps.utilities', 'hifu_planet.apps.strong_auth', 'captcha', 'registration', 'compressor', 'django.contrib.admin') Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'coop_cms.utils.RequestMiddleware', 'django.middleware.gzip.GZipMiddleware'] Traceback: File "/Users/benjamincherpas/Dev/hifu_prostate/env/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/benjamincherpas/Dev/hifu_prostate/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 198. "returned None instead." % (callback.module, view_name) Exception Type: ValueError at /create-alias/10/ Exception Value: The view hifu_planet.apps.cms.views.create_alias.create_alias didn't return an HttpResponse object. It returned None instead. Hope I was clear, thank you. -
Django ready in AppConfig is stuck when starting a thread
I'm trying to create a background thread in my Django project. In order to do that I created a new app under my project and defined an AppConfig as follows: class WebhooksConfig(AppConfig): name = "my_app" def ready(self): super(WebhooksConfig, self).ready() MyListener.start() The MyListener.start() method looks as follows: @classmethod def start(cls): worker = Thread(target=cls.my_entry_point) worker.start() I would expect that after worker.start() the main thread will be freed and the ready method will be finished. Instead, it looks like this tread start is hanging the entire app. If I add daemon=True to the Thread initialization, it works. But I don't want my thread to be daemonized. -
Django deployment media files not loading but Static files are working fine
Hey im hosting Django on Digitalocean ubuntu server using nginx and gunicorn. static files are working fine but media files (images) are not loading. urls.py urlpatterns = [ ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/' nginx confix server { listen 80; server_name 142.93.42.87; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/projdir; } location /media/ { root /home/user/projdir/media; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
Django: Annotate across three models
I'd like to make an intricate annotate call over a QuerySet and I don't know how to build it. Could you help? I'll try to simplify my setup: I have 3 models: Movie, Actor and Casting. Each Casting has a foreign key to a Movie and an Actor, and a CharField for role. For example, a Casting can be that Johnny Depp played Jack Sparrow in Pirates of the Caribbean. I'd like to get a list of movies, and to each movie there will be an annotation saying the role that Johnny Depp played in that movie. If he didn't play in that movie, it should be None. Note that I'm giving a specific actor, I don't want to go over all actors. -
Recording audio in Django model
Hey i would like to record an audio as a voice note in one of my models: class ShipPhoto(models.Model): user_name = models.ForeignKey(User, on_delete=models.CASCADE) photo = models.ImageField() voice_record = ?????? carplates = models.CharField(max_length=20) So that when i open the form_template i can click the voice record and upload the recorded message to my model. I've checked this link https://github.com/voxy/django-audio-recorder but when i install it using pip command it automatically uninstalls my current version of django (2.0.8) and downgrades to 1.8 ... Is there any other solutions how can i do it ?? -
Statsd on Amazon linux AMI 2018
I am trying to collect metrics from my djnago app and display the same on Graphana.I am using Amazon AMI for my django app, and I am stuck on how to use the monitoring packages statsd and collectd. I don't know how should I proceed , read the blog but it was not helpful. Any suggestions? -
Use many-to-many related field count to sort list view
I managed to get the count of my related many-to-many field into the list view but I'm failing to use it to sort the list. class GuestAdmin(admin.ModelAdmin): inlines = (GuestEpisodeAdmin, TopicGuestAdmin, JobGuestAdmin) exclude = ('episodes', ) list_display = ('name', 'twitter', 'gender', 'medium', 'episode_count') def episode_count(self, obj): return obj.episodes.all().count() I have seen similar stuff being done with custom querysets but I don't have a clue how to get my count into that. I'm not even sure if the way I do the count is the best way to do it. -
Django model : save object with custom field
I would like to know how I can do that : save an object in my database through Django model with custom field. This is my modelclass : class Document(EdqmTable): language = models.CharField(max_length=2, verbose_name=_('language'), choices=LANGUAGE_CHOICES, null=False) format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES, null=False) title = models.CharField(max_length=512, verbose_name=_('document title'), null=False) publication = models.ForeignKey(Publication, verbose_name=_('publication title'), null=False, related_name='documents') class Meta: verbose_name = _('document') verbose_name_plural = _('documents') def save(self, *args, **kwargs): self.title = f"{self.publication.pub_id}-{self.format.upper()}" super(Document, self).save(*args, **kwargs) I have a save method, which let to define my field title with combination between two fields. title field is hidden in my django form and is set automatically by Django. But, up to now, it doesn't work because my object is not saved into my database. Something is wrong in my save function ? -
Django multi level model access
I would like to perform the following operations: 1) I want to register a student to courses 2) I want to enter course score for student depending on their registration 3) I want to calculate the total score by the student in every courses he registered -
[Pdb results attached]Constraint works in Table B 'matching query does not exist' in Table A - Python/Django
I have several tables as below, which was created according to a third-party system, application also runs under the database of this system(oracle). Constraint failed in TableA, but it works in Table B, supposed I want to display e.name in Table B with code of b.c.d.e.name, the fronted page displayed exact data, and fronted page displayed None in Table A with code of a.b.c.d.e.name, class A(models.Model): a_id = models.IntegerField(primary_key=True) b = models.OneToOneField('B', models.DO_NOTHING, related_name='+') class B(models.Model): b_id = models.IntegerField(primary_key=True) c = models.OneToOneField('C', models.DO_NOTHING, related_name='+') class C(models.Model): c_id = models.IntegerField(primary_key=True) d = models.OneToOneField('D', models.DO_NOTHING, related_name='+') class D(models.Model): d_id = models.IntegerField(primary_key=True) e = models.OneToOneField('E', models.DO_NOTHING, related_name='+') class E(models.Model): e_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=64) Results of pdb as below: (Pdb) B.objects.using('third_party_db').get(c__d__e__name="Dog") *** general.models.B.MultipleObjectsReturned: get() returned more than one B -- it returned 1673! (Pdb) A.objects.using('third_party_db').get(b__c__d__e__name="Dog") *** general.models.A.DoesNotExist: A matching query does not exist. (Pdb) A.objects.using('third_party_db').get(b__c__pk=1) *** general.models.A.DoesNotExist: A matching query does not exist. (Pdb) A.objects.using('third_party_db').get(b__f__pk=1) *** general.models.A.MultipleObjectsReturned: get() returned more than one A -- it returned 18! -
Django REST Framework: Custom Fields from JSON
I'm trying to create a universal model which will take in a product name, its options, and the price. Here is the example json I want to send. { "product": "jacket", "options": { "color": ["purple"], "size": ["s", "m", "l"], (I want the ability to add unlimited strings here) }, "price": 234 } My problem is that I need to generalize the color and sizes. IE, options should contain a CharField, option_name, which could be repeated over and over with different option names with unique values. Is there a way to do this using more data tables or a built in Django REST functionality? -
Atomic transactions in DRF action?
I am trying to get into Django atomic transactions at first time. I wonder if there is a possibility to use it something like this: class TaskViewSet(MultiSerializerViewSet): @transaction.atomic @action(methods=['PATCH'], detail=True) def move_task(self, request, pk): # making queries, trying to update them, roll back if last one fails. return Response("message: SUCCESS", status=_status.HTTP_200_OK) I have searched a bit - there is some information about how to use transactions but I did not find any info if it is possible to use them with DRF. -
Use value from one query in another using pymongo
I am using pymongo with django. I want to use the result of one query in another. This is what I have so far. But I am getting errors when I try userInfo = myUL.find( { 'action': "c_r" , 'data.theRID': int(request.GET['audit_run_id']) }, { 'data.theRID': 1 , 'user_email': 1 , "_id": 0} ).sort("user_email", 1) res = mycol.aggregate([ { '$unwind': '$tags' }, { '$match': { 'tags.tag.name':'A A', 'aR': userInfo.theRID } }, { '$project': { 'url': 1, '_id': 0 } } ]) I want to use the data.theRID in the aR column of mycol. Please help. I also want to return values of both queries in a HttpResponse. This is what I have but again, I am not sure I am doing the right thing: userInfo = list(userInfo) res = list(res) return HttpResponse(dumps(res, indent=0), content_type='application/json') return HttpResponse(dumps(userInfo, indent=0), content_type='application/json') I definitely doing something wrong. I am new to Python and MongoDB. Please help! -
Accepting a different field in POST in Django REST Framework
If I have the following Dango model and Django REST serializer: # model class Attribute(models.Model): name = models.CharField(max_length=50) code = models.CharField(max_length=50) value = models.IntegerField(default=0) # serializer class AttributeSerializer(serializers.ModelSerializer): name = serializers.CharField() code = serializers.CharField() value = serializers.IntegerField() class Meta: model = Attribute fields = ('name', 'code', 'value', 'group') Is it possible to accept a different field during the PUT or POST to update the model? for example, could it accept attribute_value and use that to update the value field?