Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django validate unique charfield in admin console
I have 2 models with a CharField called path. On one of them I need to force it to end with / and on the other one anything but /. Also this field has to be unique and indexed. Here is the solution I came up with so far: Dir model (must end in '/') # The path for sorting, e.g. /stuff/00-1/. Must be unique and is indexed for performance. path = models.CharField(max_length=75, unique=True, db_index=True, blank=False, validators=RegexValidator(regex=r'^/[A-Za-z0-9/-_]+/$', message="Please enter a valid Dir Path")) ... def save(self, *args, **kwargs): # If the path does not end in "/" add it. if not self.path.endswith("/"): self.path += "/" if not self.path.startswith("/"): self.path = "/" + self.path # print the result print("Saving path {}".format(self.path)) super(Dir, self).save(*args, **kwargs) # Call the "real" save() method. I have attempted a try except around the call to super() however that changes nothing. How to I tell the admin console to validate the data so I get a not unique error before it saves and crashes so the admin can change it? TL;DR how do I get the red line to appear above a charfeild in the admin console if it fails custom regex validation? -
django model manager error
i am trying to override the all() method, to filter the querrySet. but it throws an error saying. typeError: module.__init__() takes at most 2 arguments (3 given) this is my modelmanager class PostManager(models.manager): def all(self): return super(PostManager, self).filter(draft=False).filter(publish__lte=timezone.now()) and this is the model class post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) title = models.CharField(max_length=50) content = models.TextField() publish = models.DateField(auto_now=False, auto_now_add=False) draft = models.BooleanField(default=False) objects = PostManager() def __str__(self): return self.title -
Mock external call in all unit test
I need some help to mock a function which is getting an external call. My function send_slack_message is in a module called slack_utils. This is the structure of my project (which is a django project) <my_project> | - helpers | | | - _init_.py | - slack_utils.py | | | - def send_slack_message(.....): | - tests - _init_.py - test_slack_message.py I would like to mock send_slack_message in init module of the tests package do not take care anymore of external calls in all tests I am going to write in my test_*.py modules. Any helps of good idea to achieve my goal would be really appreciated. Thanks. Walter -
How can I require two - and only two - of four foreign key fields in a model to be filled?
I have a simple model with two objects. One object type (1) just stores information. The other (2) stores information and connections between objects. The connection can be 1-1, 1-2, or 2-2. Object 2 has four foreign key fields (to and from object 1 & 2). Because a connection can only be made between two objects, I want to specify in my model that not all four foreign keys can be filled in at the same time, but only two in combination. The others should be left blank. How can I achieve this? -
Manager isn't available while setting up django-fmc
I'm trying to get django-fmc set up with Django (v 1.97, Python v2.7.12, djangorestframework v3.3.3) to handle storing registration ids and sending notifications to devices. I am following the tutorial they provide but it doesn't seem to be working. I am getting the following error when running my local server and python manage.py fcm_urls: ... File "C:\Work\Dev\LiveTracking\Api\app\views.py", line 50, in DeviceViewSet queryset = Device.objects.all() File "C:\Work\Dev\LiveTracking\Api\env\lib\site-packages\django\db\models\manager.py", line 277, in __get__ self.model._meta.swapped, AttributeError: Manager isn't available; 'fcm.Device' has been swapped for 'app.MyDevice' I don't want to add additional fields to the MyDevice model for now. I've looked all over but can't fix this error. If anyone can shed some insight into this error it would be much appreciated. Here are some of my code snippets: settings.py INSTALLED_APPS = ( 'fcm', ) # Firebase Cloud Messaging Key FCM_APIKEY = 'AIzaSyCaqHZIcaGDOpfTZUmAHEowsqD-fCtow6A' # Location of device model FCM_DEVICE_MODEL = 'app.MyDevice' serializers.py from fcm.models import Device class DeviceSerializer(serializers.ModelSerializer): class Meta: model = Device fields = ('dev_id','reg_id','name','is_active') views.py from rest_framework import viewsets from fcm.models import Device from fcm.serializers import DeviceSerializer class DeviceViewSet(viewsets.ModelViewSet): queryset = Device.objects.all() serializer_class = DeviceSerializer urls.py from rest_framework import routers from fcm.views import DeviceViewSet router = routers.DefaultRouter() router.register(r'devices', DeviceViewSet) urlpatterns = [ url(r'^v1/', … -
Override django allauth post_save method to add referral param tracking
I trying to add the ability to track referral urls to my django webapp using django-allauth and django-referral apps. Basically, I want to somehow store the ref GET param which brings the user to my website in some cookie and save this when he/she registers. My attempt to integrate the two apps has been to add the below function: SocialAccountAdapter(DefaultSocialAccountAdapter): ... def save_user(self, request, sociallogin, form=None): u = super(SocialAccountAdapter, self).save_user(request, sociallogin, form) UserReferrer.objects.apply_referrer(u, request) return u However, this doesn't seem to be working and the view becomes unresponsive. I am also unable to see any errors. So can somebody please tell me if there's something that I am doing wrong here and/or are there any other approaches to get such functionality? -
Table results link to datatable Django/Python
I have a table in my Django project that makes a .count() filtering data from a model to know the number of every status from orders as is shown below: Here is my code: Template HTML <ol class="breadcrumb breadcrumb-2"> <li><a href="/msr/main"><i class="fa fa-home"></i>Home</a></li> <li class="active"><strong>Non-Progression</strong></li> </ol> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading clearfix"> <h3 class="panel-title">Non-Progression Overview</h3> <ul class="panel-tool-options"> <li><a data-rel="collapse" href="#"><i class="icon-down-open"></i></a></li> </ul> </div> <div class="panel-body"> <div class="table-responsive"> <table id="sum_table" class="table table-bordered"> <thead> <tr class="titlerow"> <th><center><img title="" alt="" src="{% static 'images/line-graphic.png' %}"></center><br><center><b>Non-Progression</b></center></th> <th colspan="2"><center><img title="" alt="" src="{% static 'images/supplycom.png' %}"></center><br><center><b>Supply Complete</b></center></th> <th colspan="2"><center><img title="" alt="" src="{% static 'images/landing.png' %}"></center><br><center><b>Allocated</b></center></th> <th colspan="2"><center><img title="" alt="" src="{% static 'images/packing.png' %}"></center><br><center><b>In Picking</b></center></th> <th colspan="2"><center><img title="" alt="" src="{% static 'images/packed-icon.png' %}"></center><br><center><b>Pick Complete</b></center></th> <th colspan="2"><center><img title="" alt="" src="{% static 'images/packed.png' %}"></center><br><center><b>Pack Complete</b></center></th> <th colspan="2"><center><img title="" alt="" src="{% static 'images/danger.png' %}"></center><br><center><b>Line Prod Issues</b></center></th> <th colspan="2"><center><img title="" alt="" src="{% static 'images/record.png' %}"></center><br><center><b>Loaded no docs</b></center></th> <th colspan="2"><center><img title="" alt="" src="{% static 'images/contract.png' %}"></center><br><center><b>Loaded with docs</b></center></th> <th colspan="2"><center><img title="" alt="" src="{% static 'images/trucking.png' %}"></center><br><center><b>Shipped</b></center></th> </tr> </thead> <thead> <tbody> <tr class="odd"> <td> DATE </td> <td><center>OTS </center></td> <td><center>LTA </center></td> <td><center>OTS </center></td> <td><center>LTA </center></td> <td><center>OTS </center></td> <td><center>LTA </center></td> <td><center>OTS </center></td> <td><center>LTA </center></td> <td><center>OTS </center></td> <td><center>LTA </center></td> <td><center>OTS </center></td> <td><center>LTA </center></td> … -
ProgrammingError after setting up postgres db
I am getting this error trying to save an instance in the admin page I have tried Everything was working fine before setting up postgres db. Am I missing something ? -
How to relate two Django models via Django Rest Framework Serializer using ForeignKeys
I have three models: class Ordering(models.Model): schedule = models.ForeignKey(Schedule, on_delete = models.CASCADE) order_number = models.IntegerField() room = models.ForeignKey(Room, on_delete = models.CASCADE) class TransactionDateTime(models.Model): room = models.ForeignKey(Room, on_delete = models.CASCADE) end_dy = models.DateField(blank = True, null = True) percentage = models.DecimalField(default = Decimal('0.00'), decimal_places = 2, max_digits = 4) class Room(models.Model): room_name = models.CharField(max_length = 200) barcode_name = models.CharField(max_length = 200) a view class RoomListMixin(object): serializer_class = SimpleSerializer2 class RoomListViewSet(RoomListMixin, generics.BulkModelViewSet): def get_queryset(self): num = self.kwargs['sc'] s1 = Schedule.objects.get(pk = num) queryset = s1.ordering_set.all() return queryset and a serializer associated with the above view that works perfectly and renders my desired API results. class SimpleSerializer2(BulkSerializerMixin, ModelSerializer): room_pk = serializers.CharField(source = 'room.pk') room_name = serializers.CharField(source = 'room.room_name') barcode_name = serializers.CharField(source = 'room.barcode_name') user = serializers.CharField(source = 'schedule.user') schedule_id = serializers.CharField(source = 'schedule.pk') class Meta(object): model = Ordering list_serializer_class = BulkListSerializer fields = ('pk', 'schedule_id', 'room_pk', 'room_name', 'barcode_name', 'user', 'schedule_id') But..i need to link the TransactionDateTime model to the above serializer based on ForeignKey 'Room' using the Django Rest Framwork, since both my TransactionDateTime and Ordering model share the same Foreign Key. After linking I would then like to add the percentage field in the TransactionDateTime model to the above serializer. How do … -
Python/ Django- NoReverseMatch at
I am working on a project that has been written in Python/ Django, and recently fixed a bug within the project (using a local Git branch dateReceived to make the changes and fix the bug, then merging the dateReceived branch with master on my local machine). I tested that the bug had been fixed on my local master branch, and when I was happy that it had, I pushed my changes to the server. However, when working with the live version now, it seems that doing this has broken another part of the website, and when I click the button that takes you to the URL `http://.../adds_omits/, I get an error page displayed in the browser that says: NoReverseMatch at /.../adds_omits/ Reverse for 'export_csv' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'costing/(?P[0-9]+)/export-csv/$'] and that there was an Error during template rendering Reverse for 'export_csv' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'costing/(?P[0-9]+)/export-csv/$'] This error message highlights the following line from the template that this URL renders: <a class="button m-r-md" href="{% url 'costing:export_csv' budget.id %}">Export to Excel</a> and the 'Traceback' shows the following messages in bold: return permission_required(required_permission)(view_func)(request,*view_args,**view_kwargs) & return render(request, … -
REST API or "direct" database access for remote Celery/Django workers?
I'm working on a project that will have multiple celery workers on machines in different locations in the US that will communicate over the internet. Am I better off distributing my Django project to each machine and configuring them with the database credentials to my database host, or should I have a "main" Django/database host that presents a REST API for remote celery tasks and workers to hit for the database access? -
how to bring out django project from virtualenv
I have django project in virtualenv and now I am publishing it in server but the problem is I can not move project from virtualenv, when I do this then related packages inside site-package, cant be read and errors occur, how can I bring out my project from virtualenv without any issuing -
Dymanic django crispy formsets not showing client side errors before form submission
Using jquery, crispy forms, and django formsets, I am dynamically adding multiple forms to a page and submitting them together for processing. Everything is working except errors messages: when a user doesnt fill out a required field the page should show an error when they attempt to submit it. I was under the impression that crispy forms handled that automatically, but it is not. Right now, it submits but fails silently, simply skipping any forms with errors and saving all forms without errors. How can I ensure error messages are caught before submission and displayed on the page for the user to correct? I'm actually loading 4 different formsets into this but only included 1 as an example, so some of this code may look a little off but it should be enough to get the gist of what I'm trying to do. Html/jquery for rendering forms: $('.add-item').click(function(ev) { ev.preventDefault(); template = $('#note-template') total_forms = $('#id_n-TOTAL_FORMS') var count = parseInt(total_forms.val()) var tmplMarkup = template.html(); var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count); $('div#forms-container').append(compiledTmpl); // update form count total_forms.attr('value', count+1); $('.datepicker').datepicker() $('.delete-form').click(function(e){ $("<input type='hidden' value='True' />").attr('name', 'n-'+form.attr('id')+'-DELETE').appendTo(form) } form.hide() }) }); <a href="#" id='add-note' class="btn add-item">Add Comment</a> <form action="." method="post"> {% csrf_token %} {{ … -
Django render_to_string adding '\n' to XML template
I am trying to render a xml template to a string in the view to make a soap request to a web service. When I do loader.render_to_string('app/services/soap/item_update.xml', context, None), the string I get have break lines (\n) where I have pressed enter. Below is an example. Ex XML Code: <name>Das</name> <city>Col</city> Corresponding string: '<name>Das</name>\n <city>Col</city>' The type of the rendered response is <class 'django.utils.safestring.SafeText'> Is there a way to render the string without the line breaks, since making a Soap request with it sends a 400 response? -
Master-Detail Django Forms
I have been struggling mightily with Master-Detail forms in Django. I have done a number of online tutorials but have yet to find a complete tutorial which completely explains models, views, templates, URL patterns related to master-detail forms. If someone could point me toward a good comprehensive book chapter or tutorial, I would be much appreciated. THX. -
Query for only part of objects of related_name(from forein key)
I have to models: class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Entry(models.Model): blog = models.ForeignKey(Blog,related_name='entries') headline = models.CharField(max_length=255) body_text = models.TextField() I would like to get all Blogs and inside each blog I would have that all entries where headline is 'bike'. So the output will be list of all Blogs and the blog.entries will have the filtered list of entries. -
Django query returning empty data after order_by()
I'm making queries with filter() and exclude() depending on the search criteria of the user. I'm also sorting the query according to the search if specified. Everything works fine except when the user use the exclude() function and try to sort in a related_field. It works with filter(), though. I'm using Django 1.9 and Postgresql The model simplified is the following: class Project(models.Model): name = models.CharField(max_length=175) class Meta: ordering = ['name'] db_table = 'project' class Summary(models.Model): mykey = models.CharField(max_length=20, primary_key=True) external_order_id = models.ManyToManyField('Project', blank=True) The query project = InventoryProject.objects.get(name='') # with exclude # this one returns [], but if I do .count() it returns the correct number of rows queryset.annotate(num_projects=Count('external_order_id')).exclude(external_order_id=project, num_projects=1).order_by('external_order_id') # with filter # this one works like a charm queryset = queryset.annotate(num_projects=Count('external_order_id')).filter(external_order_id=project, num_projects=1) I checked the .query attribute before and after the order by and they seem very different // before (it shows all the data) SELECT "summary"."mykey", COUNT("summary_external_order_id"."project_id") AS "num_projects" FROM "summary" LEFT OUTER JOIN "summary_external_order_id" ON ("summary"."mykey" = "summary_external_order_id"."summary_id") GROUP BY "summary"."mykey" HAVING NOT ("summary"."mykey" IN (SELECT U1."summary_id" AS Col1 FROM "summary_external_order_id" U1 WHERE U1."project_id" = 1) AND COUNT("summary_external_order_id"."project_id") = 1) // after (doesn't show any data) SELECT "summary"."mykey", COUNT("summary_external_order_id"."project_id") AS "num_projects" FROM "summary" LEFT OUTER … -
Cant save python requests library's response.json() to Django's JSONField
This gave me a headache. I have a simple requests request, and a django model with a JSONField: resp = requests.post(....) my_object = ModelWithJsonField.objects.create(json_data=resp.json()) I get the error: Error binding parameter 2 - probably unsupported type. resp.json() looks like this: {u'error': u'error description'} How can I solve this? -
Use django for one page on a website?
I have a small app I would like to build as a project to learn more about web development. Its an app where people can register etc, and add information about themselves (database needed) and their location on a webmap (using leaflet library). The app will be a single page application that the user navigate to via a link on the site that today is already live. I got a comment from one i know not to use php. Since I am learning python I was thinking maybe to use that for the server side bits. Is it a good idea to use django or other python framework when it will only be used on a single page of the site, is it even possible (very green on this)? Or should i just stick to php for a project this size? Any input would appreciated -
Django Rest Framework with Self-referencing many-to-many through unable to get the through model
I am trying to get the relations and the relationship for a particular instance. I need to get both the related objects id and the relationship information. My models are based off of relationships from http://charlesleifer.com/blog/self-referencing-many-many-through/ Django 1.8.3 and Django Rest Framework 3.3.3 models.py class Person(models.Model): name = models.CharField(max_length=100) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') class RelationshipType(models.Model): name = models.CharField(max_length=255) class Relationship(models.Model): from_person = models.ForeignKey(Person, related_name='from_people') to_person = models.ForeignKey(Person, related_name='to_people') relationship_type = models.ForeignKey(RelationshipType) serializers.py class RelationshipTypeSerializer(serializers.ModelSerializer): class Meta: model = models.RelationshipType class RelationshipSerializer(serializers.ModelSerializer): relationship_type = RelationshipTypeSerializer() to_person_id = serializers.ReadOnlyField(source='to_person.id') to_person_name = serializers.ReadOnlyField(source='to_person.name') class Meta: model = models.Relationship fields = ( 'id', 'relationship_type', 'to_person_id', 'to_person_name', ) class PersonSerializer(serializers.ModelSerializer): annotated_relationships = RelationshipSerializer(source='relationships', many=True) class Meta: model = models.Person fields = ( "id", "name", 'annotated_relationships' ) I am currently getting something like this: { "id": 88, "name": "Person 88", "annotated_relationships": [ { "id": 128 }, { "id": 130 } ] } What I want looks like this, though the format doesn't need to be this way as long as I can get the relationship information: { "id": 88, "name": "Person 88", "annotated_relationships": [ { "id": 128, "relationship_type": { "name": "friend", }, "to_person_id": 34, "to_person_name": "Jeremy", }, { "id": 130, "relationship_type": { "name": "enemy", … -
OneToOneField(user) imply recreating all account?
I extended user class with a new class "Profile" using OneToOneField. It worked but now I can't reuse old account. (So user,superuser and admin). I get a "RelatedObjectDoesNotExist" Error since my old account do not have any "Profile". I suppose their is an other way than recreating accounts (Because I can't imagine it in production every new version) but I can't figure out how to update every old account. Does someone has any clue? -
Redirection: mod_wsgi and django
following this guide, I have setup Mailman 3 with Apache and mod_wsgi on a Debian server. The .conf-file of my virtualhost: ErrorLog /var/log/mailman-web/mailman-web.log CustomLog /var/log/mailman-web/mailman-web_access.log combined WSGISocketPrefix run/wsgi <VirtualHost *:80> ServerName XXXXXXX ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # Here, use the value of the STATIC_ROOT variable in your Django configuration file (production.py) Alias /robots.txt /usr/local/mailman/mailman-bundler/var/mailman-web/static/hyperkitty/robots.txt Alias /favicon.ico /usr/local/mailman/mailman-bundler/var/mailman-web/static/hyperkitty/favicon.ico Alias /static /usr/local/mailman/mailman-bundler/var/mailman-web/static <Directory "/usr/local/mailman/mailman-bundler/var/mailman-web/static"> Order deny,allow Allow from all Require all granted </Directory> WSGIScriptAlias / /usr/local/mailman/mailman-bundler/bin/mailman-web.wsgi WSGIDaemonProcess mailman-web display-name=mailman-web maximum-requests=1000 processes=1 threads=1 python-path=/usr/local/mailman/venv/lib/python2.7/site-packages <Directory "/usr/local/mailman/mailman-bundler/bin"> <Files mailman-web.wsgi> Order deny,allow Allow from all Require all granted </Files> WSGIProcessGroup mailman-web </Directory> </VirtualHost> The problem I have with this setup is, when I go to http://myhost/ the wsgi script redirects my browser to http://myhost/archives. I would like to have http://myhost/ redirected to http://myhost/mailman3 and not http://myhost/archives. Trying to find out where mailman decides to return the archives subdirectory, I looked into the wsgi script defined in the apache .conf-file but there is not much more happening then importing some classes and calling another script. Following this script I landed in the file ´./eggs/Django-1.10.4-py2.7.egg/django/core/handlers/wsgi.py`, specifically this part: 148 class WSGIHandler(base.BaseHandler): 149 request_class = WSGIRequest 150 151 def __init__(self, *args, **kwargs): 152 … -
Django Compressor not using STATICFILES_FINDER from settings
I'm trying to use Django Compressor, which seems pretty straight-forward, but for some reason I keep getting an error, specifically: When using Django Compressor together with staticfiles, please add 'compressor.finders.CompressorFinder' to the STATICFILES_FINDERS setting My settings.py file includes the following: DEBUG = True INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... 'compressor', ) STATIC_URL = '/static/' STATICFILES_FINDER = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder' ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, '_static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') COMPRESS_ENABLED = True I'm not sure if this is a compatibility issue with Django 1.10 (Django Compressor changelog states it is compatible with 1.10), or if Django Compressor simply is broken, since I've clearly added 'compressor.finders.CompressorFinder' to the STATICFILES_FINDERS setting. I've also tried with DEBUG=False. Any help is appreciated. -
Django/Python Model/Form class design
Can someone provide advice on the best way to structure my model and form classes. While I do have 25+ years experience in software development (primarily scientific visualization), I don't have much experience in relational database design. Here is what I want to do... I'm trying to develop a Django web app for my tennis club for scheduling team matches, I'm planning on the having the following classes: Team - will contain a captain, list of players and a list of matches Player - will contain the players name, cell, email Match - will contain a date, opponent, location and result Now, here's where the real question comes in...I want each player to be able to indicate their availability for each match (Yes, No, Maybe), and I want to be able to assign each player a position for each match (there are 2 singles courts and 3 doubles courts). I would prefer this be in a simple table format that looks something like this: where each cell in the body of the table is a drop down, allowing the user to choose Y, N, or ? (only for themselves), or the team captain to choose S1,S2,D1,D2, or D3 (for everybody) … -
Postgres index together or hash field with index it?
I have a question. For example I have a Django model with 10 fields, which describe a change of other objects. While I'm creating new change, I must find if change already exists. This is because changes are generating in parallel. When I checking it, I use filter on 8 fields (some ints, some strings). And now I have index_together on it, but I think what if I will generate hash from this 8 fields and insert as 11 field in model, then just filter using this field? Of course, on hash field will be an index.