Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django distinct() not returning distinct values
I have a Session model like this: class Session(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name="sessions") flavor = models.ForeignKey(Flavor, null=True, blank=True, on_delete=models.CASCADE, related_name="sessions") .... And I'm trying to run a query: sessions = Session.objects.all().values('flavor__pk', 'user__pk').distinct() But when I then print the sessions object I get this: <QuerySet [{'user__pk': 14544, 'flavor__pk': 1}, {'user__pk': 14544, 'flavor__pk': 1}, {'user__pk': None, 'flavor__pk': 30}, {'user__pk': 193, 'flavor__pk': 30}, '...(remaining elements truncated)...']> Which, if you look closely, the first two entries are exactly the same {'user__pk': 14544, 'flavor__pk': 1}! Isn't this supposed to be distinct? -
How to store None as JSON 'null' rather than SQL NULL?
I'm using contrib.postgres.fields.JSONField to store some JSON data with Django 1.11. Contrary to the convention described in this answer, I'd like to store None as JSON. However, Django by default tries to store None as SQL NULL, and errors if I set the field to null=False. Is there any way to get Django to store None as 'none'::jsonb? -
Can't overwrite manager method on django
I have this manager: class ConfigValueManager(models.Manager): def get(self, key): config_value = self.filter(key=key).first() if config_value: type_caster = locate(config_value.type) return type_caster(config_value.value) return config_value def set(self, key, value): self.filter(key=key).update(value=value) def set2(self, key, value): qs = self.filter(key=key) if qs: qs.update(value=value, type=type(value).__name__, company=self.instance) else: self.create(key=key, value=value, type=type(value).__name__, company=self.instance) the problem is that I can't overwrite set. The method is still coming from the parent, even though I've created set on the child. Funny thing is that get and set2 are fine. My question is how can I overwrite set and why this happens? -
manytomany Implementation in Django (admin issue)
I've spent a lot of time reading through the other questions on this subject and the Django docs. I'm relatively new to python and completely new to django and webdesign. I'm attempting to set up the admin site so that the leader of the project I'm working on can enter/edit the data she needs. I'm trying to implement a manytomany relationship between two models: Subordinate Metaphor and Myth. models.py class Mytheme(models.Model): myth_id = models.AutoField(primary_key=True) mytheme = models.CharField("Mytheme",max_length=1500, blank=True, null=True) superord_myth = models.CharField("Superordinate Myth", max_length=1500, blank=True, null=True) myth_dhuy = models.CharField("D'huy Myth",max_length=600, blank=True, null=True) deities_involved = models.CharField("Deities Involved",max_length=800, blank=True, null=True) myth = models.CharField("Myth",max_length=1000, blank=True, null=True) myth_comment = models.CharField("Comment",max_length=1500, blank=True, null=True) class Meta: managed = True db_table = 'mytheme' ordering = ['myth_id'] verbose_name = 'Mytheme' class Subordinatemet(models.Model): submet_id = models.AutoField(primary_key=True) submetaphor = models.CharField("Subordinate Metaphor", max_length=1500, blank=True, null=True) sub_type = models.CharField("Type",max_length=200, blank=True, null=True) sub_semanticfield = models.CharField("Semantic Field",max_length=1500, blank=True, null=True) sub_metanet_no = models.BigIntegerField("Metanet Number",blank=True, null=True) sub_metanet_frame = models.CharField("Metanet Frame",max_length=1500, blank=True, null=True) sub_dhuy_no = models.BigIntegerField("D'huy Number",blank=True, null=True) sub_dyson_ref = models.CharField("Dyson Reference",max_length=1500, blank=True, null=True) sub_johnlakoff_ref = models.CharField("Johnson/Lakoff Reference",max_length=1500, blank=True, null=True) sub_bibliography = models.CharField("Bibliography",max_length=2000, blank=True, null=True) sub_comment = models.CharField("Comment", max_length=2000, blank=True, null=True) ordinacy = models.SmallIntegerField("Ordinacy",blank=True, null=True) myths = models.ManyToManyField(Mytheme) class Meta: managed = True db_table = 'subordinatemet' ordering … -
Django - Difference b/w Django-rpy2 & rpy2
Django is showing two rpy2 related packages Django-rpy2 rpy2 Are they both different like i am familiar with rpy2 but what does Django-rpy2 offer? I am unable to find something in django-rpy2 documentation. What is it all about? Thanks -
Loading Django static content from S3 giving "Unsafe attempt to load URL. Domains, protocols and ports must match."
I have my static files on S3, and when a JS script tries to load a JS library I'm using: Unsafe attempt to load URL <URL> from frame with URL <URL>. Domains, protocols and ports must match. Unsafe attempt to load URL https://s3.amazonaws.com/<bucket_name>/static/pixie/assets/icons/merged.svg from frame with URL https://<mydomain.com>/images/pixie/d71400cf-7b13-4a39-9e6d-a139f8c96416/. Domains, protocols and ports must match. I've put a CNAME to the bucket so it would sit behind s3.<mydomain>.com but that did not solve it. Adding an SSL cert + Cloudfront didn't do it either. For these JS files to load, will I have to have those on the same instance as my Django project? -
Django insert data to model with foreign key
I am using django models and am running into issues. I have a couple of models that I am trying to load data to, one with a foreign key to another. I will use two models as an example, but the hope is that I can write the code so that it will generalize to work for models with different names and different field names. The models look as follows: class ProgramInfo(models.Model): program_code = models.CharField(max_length=5, primary_key=True) ... class StudentInfo(models.Model): ... program_code = models.ForeignKey('ProgramInfo', on_delete=models.PROTECT) I also have a dictionary called _model_dict with the field names of StudentInfo as the keys and the values being the values I want to put in the model. When I run _model.objects.update_or_create(**_model_dict) It tells me Cannot assign "'ABCD'": "StudentInfo.program_code" must be a "ProgramInfo" instance. Even though that value exists in the ProgramInfo table. I have no issue inserting data to models without foreign keys using this same method. As I understand it the value for the key in _model_dict of the foreign key field should not just be the value for a single field, but an object of the model the foreign key links to. I tried singling out the foreign key fields in order … -
Rendering a Django View of an OpenAPI (Swagger) json file?
I'm trying to display a custom swagger schema as a json that I created using http://editor.swagger.io In my urls.py I have schema_view = get_custom_swagger_view() urlpatterns = [ url(r'^$', schema_view), In get_custom_swagger_view: f = open("swagger.json") json_dict = json.load(f) schema = coreapi.Document(content=json_dict) But got stuck there, because I'm not exactly sure how to go from a coreapi object to a django view. I was previously using the auto-generated swagger docs, using get_swagger_view() and that worked great, but wanted to try to use a custom written json file for flexibility instead. Any help would be appreciated! -
Filtering the filter: limiting choices in django admin filter by user privileges
OK, so I now can limit choices available in the change form as follows: def formfield_for_foreignkey(self, db_field, request, **kwargs): from login.models import Room groups = [group.name for group in request.user.groups.all()] if 'principal' in groups: schoolname = request.user.principal.school.name if db_field.name == 'room': print("match") kwargs['queryset'] = Room.objects.filter(school__name=schoolname) return super().formfield_for_foreignkey(db_field, request, **kwargs) list_display = ('surname','givennames', 'room') list_filter = ('room',) That is, the above succeeds in showing the user only students enrolled in his or her school. My trouble is that the user still sees rooms from schools they are not connected to on the list_filter, which is ignoring formfield_for_foreignkey So instead of seeing a half dozen classrooms as choices on the filter, the pulldown shows hundreds of classrooms, for all the schools in the district. I have tried to find an answer of comparable simplicity, but nothing has presented itself. What i'd like is something like formfield_for_foreignkey to apply to my filter choices. I want to filter the choices for the filter! Little wonder google isn't helping! This is hard to express clearly, so I will repeat myself in the hopes that there's some clarity in my redundancy. I am trying to filter the choices available for the user to filter on, to … -
Django: how to get the following query
I have the following Django models: class Ingredient(models.Model): name = models.CharField(max_length=200) cost_per_kg = models.DecimalField(max_digits=19, decimal_places=10 class Recipe(models.Model): name = models.CharField(max_length=200) qty_in_kg = models.DecimalField(max_digits=19, decimal_places=10) #qty_in_kg quantity of preparation class RecipeIngredients(models.Model): ingredient = models.ForeignKey(Ingredient) qty_in_kg_rec = models.DecimalField(max_digits=19, decimal_places=10) #qty_in_kg_rec: required to make qty_in_kg I want to get the total cost for making the Recipe. How to get a queryset of recipes with extra column containing the total cost. -
How to optimize Django ModelChoiceField when I have more then 10,00,000 record
I am using ModelChoiceField to populate all the value in html(select) field. To optimize that i am using select2 Ajax method to populate data on type but When I want to save the selected form data into model it is not saving bcz i have add below code into form field1 = forms.ModelChoiceField(queryset=SomeClass.objects.none()) Is there any way to save and retrieve the value on the form? -
Integrating Django app with Wordpress site
We have a Wordpress site, and we want to integrate a Django app on a page. Of course, the best solution would be to make the entire site in Django. Is it possible to make abc.com/blog go to our WP blog and abc.com/app go to our Django app? Or, does it make more sense to have app.abc.com go to the Django app, keeping the clean abc.com for the WP blog? Additionally, in both these scenarios, is it possible to have one set of credentials to carry over between sites? The person that will be handling the blog and the Django app will be separate. -
How can I use a batch file to run Vagrant commands, but leave me connected to Vagrant once finished?
Here's what I have in the batch file so far: set root="C:\Users\esohlberg\lwebsite" cd %root% vagrant up vagrant ssh -- -t "source lw/bin/activate && cd /vagrant/; ./manage.py runserver 0.0.0.0:8000" cmd /k Once Vagrant is up, I activate a virtualenv, cd into the right place, and run a server. Executing this takes me all the way to the server running, where I can see System check identified no issues (0 silenced). August 24, 2018 - 12:33:12 Django version 2.0.3, using settings 'lwebsite.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. However, as soon as I quit with CONTROL-C, I see Connection to 127.0.0.1 closed. and I'm no longer in Vagrant. Is it possible to set up the commands in such a way that once the server is quit, I stay in the /vagrant/ directory with the connection still up and Vagrant's virtualenv still active? This would allow me to manage the site or run the server again with less hassle. I've already looked at https://www.vagrantup.com/docs/provisioning/shell.html, but the examples seem to show commands executed only during provisioning, which I don't want to do every single time I execute this file. -
Django Stripe webhook json data how to view that data in admin
I can now send the webhook and it get received and return a 200 status to Stripe, but i dont understand how to get the information in the json. { "id": "evt_1D2j5jEiQxrCiRvRgzqA67I2", "object": "event", "api_version": "2018-08-23", "created": 1535131739, "data": { "object": { "id": "ch_1D2j5iEiQxrCiRvR0cP0hkjE", "object": "charge", "amount": 5000, "amount_refunded": 0, "application": null, "application_fee": null, "balance_transaction": "txn_1D2j5iEiQxrCiRvRP3iahlEp", "captured": true, "created": 1535131738, "currency": "usd", "customer": null, "description": "A Django charge", "destination": null, "dispute": null, "failure_code": null, "failure_message": null, "fraud_details": { }, "invoice": null, "livemode": false, "metadata": { }, "on_behalf_of": null, "order": null, "outcome": { "network_status": "approved_by_network", "reason": null, "risk_level": "normal", "seller_message": "Payment complete.", "type": "authorized" }, "paid": true, "receipt_email": null, "receipt_number": null, "refunded": false, "refunds": { "object": "list", "data": [ ], "has_more": false, "total_count": 0, "url": "/v1/charges/ch_1D2j5iEiQxrCiRvR0cP0hkjE/refunds" }, "review": null, "shipping": null, "source": { "id": "card_1D2j5dEiQxrCiRvRfhjMg2Qc", "object": "card", "address_city": null, "address_country": null, "address_line1": null, "address_line1_check": null, "address_line2": null, "address_state": null, "address_zip": null, "address_zip_check": null, "brand": "Visa", "country": "US", "customer": null, "cvc_check": null, "dynamic_last4": null, "exp_month": 9, "exp_year": 2021, "fingerprint": "p6BWjMSv83IqjoCg", "funding": "credit", "last4": "4242", "metadata": { }, "name": "marie.pier.cm@gmail.com", "tokenization_method": null }, "source_transfer": null, "statement_descriptor": null, "status": "succeeded", "transfer_group": null } }, "livemode": false, "pending_webhooks": 1, "request": { "id": "req_VvyT7eNgvzBDku", "idempotency_key": null … -
Internet application uploaded on Heroku does not show any graphics
I uploaded the my whole application on heroku but I have a problem does not display any photos. The path to the pictures is defined in this way: src="{{blog.image.url}}" Therefore, the view should not only be local (I think so). After uploading the application, my view of django.admin it also looks strange. Please help! How can I solve this ( to be pictures will be displayed)? Can I do it without re-uploading the application (my database is completed)? -
Modify max_length for a field in an abstract model
class AbstractBaseField(models.Model): choices = models.CharField(_("Choices"), max_length=1000, blank=True) class Meta: abstract = True class TicketField(AbstractBaseField): pass TicketField._meta.get_field("choices").max_length = 5000 I'm trying to modify the max_length attribute on a field on TicketField, which inherits from an abstract model. As you see, I've monkey-patched the field on model definition and the migration is generated as expected. The field has the max_length applied correctly and I can set the value just fine via the shell, but admin validation fails as if the old max_length is still present, showing the error Ensure this value has at most 1000 characters (it has XXXX). I've inspected the max_length on the ModelForm and the Validator values at runtime, and they all use the new max_length, but somehow a validation error is still being raised. (Pdb) self.fields["choices"].max_length 5000 (Pdb) self.fields["choices"].validators[0]._constructor_args ((5000,), {}) (Pdb) self.fields["choices"].widget.attrs {u'class': u'vTextField', u'maxlength': '5000'} -
Create Django Model Instance using POST method in another Python Script
So I have a django app with some models which I can manipulate via admin and also through a client facing site, like add instances etc. However, I would like to try something a little different from that. I have a Python script that uses POST and JSON objects based on those self same models and I would like to be able to run it, connect to my django app server via a port and create new instances of my models (essentially without using Admin or my client page). Any ideas how I go about this? -
formfield_for_foreignkey seems to do nothing
I am following the scheme shown here and in various other places: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/filter_fk_dropdown.html My code looks like this: class StudentAdmin(admin.ModelAdmin): #... def formfield_for_foreignkey(self, db_field, request, **kwargs): groups = [group.name for group in request.user.groups.all()] if 'principal' in groups: school = request.user.principal.school if db_field == "room": kwargs['queryset'] = Room.objects.filter(school=school) return super().formfield_for_foreignkey(db_field, request, **kwargs) list_display = ('surname','givennames', 'room') list_filter = ('room',) I have verified that the code is invoked and school is set correctly, but no filtering on the selector is happening. That is, I can see all the room instances regardless of their respective value for school. Once deployed in the real world, the list will show far too many items, most that the user will not want to and should not see. But the filtering is not happening. Any ideas what I've missed? Is it relevant that school itself is a foreign key to room? That has worked fine in other filters Also I would like similar filtering on the list_filter on the select view, but this code isn't even invoked there. Advice much appreciated. -
Should we use tuple or list for index_together
For index_together, I was wondering, should I use tuple or list, as both seems workable. tuple class ApiMonthlyUsage(models.Model): month = models.IntegerField(blank=False, null=False) count = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: index_together = ( ('month', 'user'), ) list class ApiMonthlyUsage(models.Model): month = models.IntegerField(blank=False, null=False) count = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: index_together = [ ['month', 'user'], ] -
ListView for Database records with DetailView
Hi! I'm trying to create a ListView page with all of the records of a databse, and my goal is when you click on one of the list element you see the DetailView of that db record. The list page works, my problem is that when I go to the detail list page and nothing shows up from the data base. I use the ID of the db record in my template as href. How can redirect the data of one specific db record? The ListView works: class MyListView(ListView): context_object_name = 'object' model = models.MyModel template_name = 'my_app/my_list.html' def get_queryset(self): return MyModel.objects.filter(user_id=self.request.user) And this is my DetailView: class MyDetailView(DetailView): context_object_name = 'object2' model = models.MyModel template_name = 'my_app/my_detail.html' def get_queryset(self): return MyModel.objects.filter(user_id=self.request.user) Thanks!! -
How to insert modal dialog from python plugin[Django]?
The question is a bit confusing so let me explain. I am working on a Django project, and I have created a plugin. Here is the index.html: <html> <head> <title> {{title}} </title> <script charset="utf-8" type="text/javascript" src="https://d3js.org/d3.v3.js"></script> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"> </script> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <style> .node { cursor: pointer; color: #242323; } .link { fill: none; stroke: #706f6f; stroke-width: 3.5px; } #svgContent { position: relative; display: block; height: 800px; width: 100%; } </style> </head> <body> <div class="container"> <div class="row" style="text-align: center;"> <h1>{{title}}</h1> </div> <div class="row"> <div class="col-md-6 col-lg-6"> {% if pluginsLoad %} <form method="POST" action=""> {% csrf_token %} {% for plugin in pluginsLoad %} <button style="display:block" class="btn btn-primary" onclick="this.form.action='{% url 'loadPlugin' id=plugin.identifier %}'">{{plugin.name}}</button> {% endfor %} </form> {% else %} <h3>Nema trenutno ponudjenih ulaznih plugina</h3> {% endif %} </div> <div class="col-md-6 col-lg-6"> {% if pluginsView %} {% for pV in pluginsView %} <button style="display:block" class="btn btn-primary" onclick="location.href='{% url 'viewPlugin' id=pV.identifier %}'" >{{pV.name}}</button> {% endfor %} {% else %} <h3>Nema trenutno ponudjenih izlaza</h3> {% endif %} </div> </div> <div class="row"> <div class="container"> <div class="col-md-6"> <h2>View</h2> </div> <div class="col-md-6"> <form method="GET" action="" style="margin-top: 20px;"> Search: <input type="text" name="inputSearch"> <input class="btn btn-primary" type="submit" value="Filter/Search"> </form> </div> <div class="col-md-12"> <svg id="svgContent"></svg> … -
django-photologue not loading CSS
I have setup django-photologue, and I am trying to get it to load the default templates. I can get the HTML file loaded, but it won't load any of the CSS (mainly just bootstrap) When accessing photologue, I get the following error on the console: Not Found: /photologue/gallery/css/bootstrap.min.css [24/Aug/2018 13:42:52] "GET /photologue/gallery/css/bootstrap.min.css HTTP/1.1" 404 7311 This is odd to me, because I am almost certain that the css file is present. This is the django code including the CSS file (taken from the photologue example project): <link href="{{ STATIC_URL }}css/bootstrap.min.css" rel="stylesheet" media="screen"> The resultant HTML is: <link href="css/bootstrap.min.css" rel="stylesheet" media="screen"> No matter where I put the CSS file, I get a 404 error. I have photologue templates in myapp/templates/photologue, because for whatever reason that's what worked. The HTML I have there works fine, but the CSS just won't load. Not in it's own subfolder in the photologue templates directory, not as a subfolder in the myapp tempaltes directory, not as standalone files, not when I put them in the static folder....I've tried putting them in every possible location and reloading the site, and it makes no difference. What can I do to make my template, which loads correctly, load and … -
I can't query a table without primary key
I'm trying to query through a model in Django that has no Primary Key. I need to query though it so I can access to the Foreign keys it has. I'm just trying to do this atm and doesn't even work: chars = Characterweapons.objects.all() print(chars) And if i change Characterweapons to Weapons for example, a table with Primary Key it works. The error I get when I load the page is this: Exception Value: (1054, "Unknown column 'characterweapons.id' in 'field list'") This is my model: class Characterweapons(models.Model): characterid = models.ForeignKey(Characters, models.DO_NOTHING, db_column='CharacterID') # Field name made lowercase. weaponid = models.ForeignKey(Weapons, models.DO_NOTHING, db_column='WeaponID', blank=True, null=True) # Field name made lowercase. categoryid = models.ForeignKey(Category, models.DO_NOTHING, db_column='CategoryID', blank=True, null=True) # Field name made lowercase. quantity = models.IntegerField(db_column='Quantity', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'characterweapons' def __str__(self): return '%s %s %s %s' % (self.quantity,self.characterid,self.weaponid,self.categoryid) Anyone knows about this? Thanks in advance! -
Invalid Filter Template Error Django 1.11
This is my filter: from django import template register = template.Library() @register.simple_tag(name='addition') def addition(*args): return round(sum(list(args)), 1) This is the error: Invalid filter: 'addition' In my template: {% load static %} {% load math_filters %} This is the filter in the template: `{{ ASEL.total_time|addition:"AMEL.total_time, ASES.total_time, AMES.total_time" }}` I want the filter addition to accept any number of arguments and add the numbers together I've followed the docs to the T and still can't get the tag to register. templatetags dir is at the same level as models.py and contains __init__.py I'm totally lost. Any ideas? -
Django REST Framework create and update nested objects
I am trying to create or update a nested object if the object exists, I tried to use the create_or_update method, now the create works fine, but the update failed and said the pk already existed. My Model: class ContentHotel(models.Model): hotel_id = models.IntegerField(unique=True, blank=True, primary_key=True) star = models.FloatField(blank=True, null=True) class Meta: managed = False db_table = 'content_hotels' ordering = ('hotel_id',) def __str__(self): return str(self.hotel_id) class RateHotel(models.Model): rate_hotel_id = models.IntegerField(blank=True, unique=True, primary_key=True) content_hotel = models.ForeignKey(ContentHotel, on_delete=models.CASCADE, related_name='rate_hotels') source_code = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'rate_hotels' ordering = ('rate_hotel_id',) def __str__(self): return str(self.rate_hotel_id) My Serializers: # To handle RateHotel object operations class RateHotelSerializer(serializers.ModelSerializer): class Meta: model = RateHotel fields = __all__ # To handle nested object operations class RateHotelSerializerTwo(serializers.ModelSerializer): class Meta: model = RateHotel fields = __all__ read_only_fields = ('content_hotel',) class ContentHotelSerializer(serializers.ModelSerializer): rate_hotels = RateHotelSerializerTwo(many=True) class Meta: model = ContentHotel fields = __all__ def create(self, validated_data): rate_hotels_data = validated_data.pop('rate_hotels') hotel_id = validated_data.pop('hotel_id') content_hotel, created = ContentHotel.objects.update_or_create(hotel_id=hotel_id, defaults={**validated_data}) for rate_hotel_data in rate_hotels_data: rate_hotel_id = rate_hotel_data.pop('rate_hotel_id') RateHotel.objects.update_or_create(rate_hotel_id=rate_hotel_id, content_hotel=content_hotel, defaults=rate_hotel_data) return content_hotel def update(self, instance, validated_data): rate_hotels_data = validated_data.pop('rate_hotels') rate_hotels = list(instance.rate_hotels.all()) for key in validated_data: instance.key = validated_data.get(key, instance.key) instance.save() for rate_hotel_data in rate_hotels_data: rate_hotel = rate_hotels.pop(0) for key …