Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GraphQL with Aggregates
I have one Django model called Product with fields name, spec, sub_group and a FK to self called class I need to use GraphQL to query several aggregates - Product.objects.values('sub_group').annotate(group_count=Count('sub_group')) Product.objects.select_related('class').values('class__name', 'class__spec').annotate(class_count=Count('class')) I am experimenting with schemas but not going anywhere from django.db.models import Count from graphene import Schema, ObjectType, String, Int, List from products.models import Product class ProductNode(ObjectType): class__name = String() class__spec = String() class_count = Int() group_count = Int() class Query(ObjectType): all_classes = List(ProductNode) all_groups = List(ProductNode) def resolve_all_classes(self, args, context, info): return Product.objects.values('sub_group').annotate(group_count=Count('sub_group')) def resolve_all_groups(self, args, context, info): return Product.objects.select_related('class').values( 'class__name', 'classification__spec').exclude( class__name='').annotate( class_count=Count('class')) schema = Schema(query=Query) Need help to fix this as I dont see any examples using aggregation queries. -
Django ModelForm Bootstrap DateTimePicker
I know there are packages that could handle this, but I would like to find a direct solution using Bootstrap and Django widgets. I have a form where I give my datetime field a widget with a class that ties back to JS on the template: class MyForm(ModelForm): class Meta: model = MyModel fields = '__all__' widgets = { 'dateTimeField': DateTimeInput(attrs={'class':'datetime-input'}) } This form is turned into a modelformset so that multiple appear in a table on the webpage: MyFormSet = modelformset_factory(MyModel, extra=1, exclude=(), form=MyForm) I have the template: {% extends "base.html" %} {% load staticfiles %} {% block title %}MyTemplate{% endblock title %} {% block stylesheets %} {{ block.super }} {% endblock stylesheets %} {% block content %} <script src="//cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script> <script src="//cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="//cdn.bootcss.com/moment.js/2.17.1/moment.min.js"></script> <script src="//cdn.bootcss.com/bootstrap-datetimepicker/4.17.44/js/bootstrap-datetimepicker.min.js"></script> <script> $(function () { $('.datetime-input').datetimepicker({ format:'YYYY-MM-DD HH:mm:ss' }); }); </script> <form method="post" action=""> <div id="form_set"> <table id="formset" class="form"> {% for form in modelformset.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label }}</th> {% endfor %} </tr> </thead> {% endif %} <tbody> <tr> {% for field in form.visible_fields %} <td> {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% … -
Debugging AllAuth: social account not logging user in despite connecting successfully
Clicking the facebook login button correctly brings up the fb login popup, but after entering credentials the pop-up closes and nothing happens. Clicking the button again without reloading the pages confirms that the fb account is connected as console prints: FB.login() called when user is already connected. However no new entries appear in the user database, the user isn't redirected and is not signed in. So the problem appears to be with how AllAuth is handling things. There's no debug info appearing anywhere on the back-end, though making this somewhat difficult to figure out. Here's the allauth settings: LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' DEFAULT_FROM_EMAIL = "info@bpateman.webfactional.com" ACCOUNT_EMAIL_REQUIRED = True SOCIALACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' SOCIALACCOUNT_EMAIL_VERIFICATION = "mandatory" SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = \ {'facebook': {'METHOD': 'oauth2', 'SCOPE': ['email','public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'updated_time'], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': False, 'VERSION': 'v2.4'}} and this is the js on the login page: <script> window.fbAsyncInit = function() { FB.init({ appId : '[removed for stackoverflow]', xfbml : true, version : 'v2.10' }); FB.AppEvents.logPageView(); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = … -
OperationalError at /app/
I got an error, OperationalError at /app/ no such table: app_color . Error is Traceback is Traceback: File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/db/backends/utils.py" in execute 65. return self.cursor.execute(sql, params) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute 328. return Database.Cursor.execute(self, query, params) The above exception (no such table: app_color) was the direct cause of the following exception: File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/XXX/drilldown/app/views.py" in index 11. return render(request, 'index.html', d) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/template/loader.py" in render_to_string 68. return template.render(context, request) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/template/backends/django.py" in render 66. return self.template.render(context) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in render 207. return self._render(context) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in _render 199. return self.nodelist.render(context) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in render 990. bit = node.render_annotated(context) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in render_annotated 957. return self.render(context) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in render 1046. return render_value_in_context(output, context) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in render_value_in_context 1024. value = force_text(value) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/utils/encoding.py" in force_text 76. s = six.text_type(s) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/utils/html.py" in <lambda> 385. klass.__str__ = lambda self: mark_safe(klass_str(self)) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/forms/forms.py" in __str__ 137. return self.as_table() File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/forms/forms.py" in as_table 285. errors_on_separate_row=False) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/forms/forms.py" in _html_output 240. 'field': six.text_type(bf), File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/utils/html.py" in <lambda> 385. klass.__str__ … -
Django test client post data
I am currently writing a test for a createview and I am unable to post data to it. The object being tested has the following model class Role(models.Model): name = models.CharField(max_length=255) linked_tenant = models.ForeignKey(Tenant, blank=True, null=True) And is used in the following (generic) view class RolCreate(TenantRootedMixin, CreateView): model = RolTemplate form_class = RoleForm def get_form_kwargs(self): kwargs = super(RolCreate, self).get_form_kwargs() kwargs['linked_tenant'] = self.request.tenant return kwargs def form_valid(self, form): form.instance.linked_tenant = self.kwargs.get('tenant') return super(RolCreate, self).form_valid(form) def get_success_url(self, **kwargs): return reverse('rol_list', args=[self.request.tenant.slug]) And this is the test that I am using. class RolCreate_tests(TestCase): def setUp(self): self.tenant = get_tenant() self.role = get_role(self.tenant) self.client = Client(HTTP_HOST='tc.tc:8000') self.user = get_user(self.tenant) def test_create(self): response = self.client.post(reverse('rolcreate'), {'name' : 'new_object'}) self.assertEqual(response.status_code, 302) test_against = Role.objects.get(name='new_object') self.assertEqual(test_against, self.tenant) The assertion that throws the error is the 'get' request at the end. DoesNotExist: Role matching query does not exist. So the object is not created, yet the test does validate the 302 view, meaning a post is being made. I do not understand why this test is failing to do what it should. Could someone here help me? -
Django CorsMiddleware is not working
My server is on django, client - angular 2. I am trying to send cross domain request from client via https, but it fails with error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://instafor.my:8000' is therefore not allowed access. The response had HTTP status code 400. I have tried to use CorsMiddleware in django settings: INSTALLED_APPS = [ 'main.apps.MainConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_REPLACE_HTTPS_REFERER = True CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( 'api.instagram.com', ) CSRF_TRUSTED_ORIGINS = ( 'api.instagram.com', ) On client StaticSettings = { BASE_URL: 'https://api.instagram.com/v1/' } URLS = { userMedia: this.StaticSettings.BASE_URL+'users/{user-id}/media/recent/' } getUserMedia(user_id:any, max_id:any) { var params = new URLSearchParams(); params.set('access_token', this.accessToken); max_id && params.set('max_id', max_id); let url = this.URLS.userMedia.replace('{user-id}', user_id); return this.http.get(url, { search: params }) .map(function(res) { let result = res.json(); if(result.success) { return result.data; } else { throw result; } }) .catch((error:any) =>{return Observable.throw(error);});; } But getUserMedia fails... All answers here about this topic tell about CorsMiddleware but I already use it, maybe I do something wrong? -
bootstrap modal not recognizing model ID - delete confirmation box
I am trying to create a delete confirmation box and have made this so far using a modal, however, the message should say "are you sure you want to delete {{patient}}?", however, it only shows the name of the top patient, and it doesn't even delete the top patient. CODE: {% for patient in all_patients %} <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-body"> <!-- Name --> <h4>{{ patient }}</h4> <!-- View Details --> <a href="{% url 'patients:patientInfo' patient.id %}" class="btn btn-primary btn-sm" role="button">View Details</a> <!-- Edit Details --> <a href="{% url 'patients:patient-update' patient.id %}" class="btn btn-primary btn-sm" role="button">Edit Details</a> <!-- Delete Patient --> <input type="hidden" name="patient_id" value="{{ patient.id }}" /> <button type="submit" class="btn btn-default btn-sm" data-toggle="modal" data-target="#confirm-delete"> <span class="glyphicon glyphicon-trash"></span> </button> <!-- Modal --> <div class="modal fade" id="confirm-delete" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Confirm delete</h4> </div> <div class="modal-body"> <p>Are you sure you want to delete {{ patient }}?</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">No</button> <form action="{% url 'patients:patient-delete' patient.id %}" method="post" style="display: inline;"> {% csrf_token %} <button type="button" class="btn btn-default" data-dismiss="modal">Yes</button> </form> </div> </div> </div> </div> </div> </div> </div> {% cycle '' '' '' '' '' '<div class="clearfix … -
Django SubQuery Error when Building a Recipient List for send_mail() based on Custom Permission
I am trying to code a recipients list for send_mail() that will query for users with a custom permission and place them in the list. The purpose is to use Django admin to make it easier on the user to place users into a group with this permission to receive the email. I am receiving this more than one row returned by a subquery. I am using modelBase which has a few child models so the custom permission attaches it self to more then one model. How can I adjust my code to clear this error and produce the recipients list I need. Here are my models.py and views.py. I apologize if the formatting is off, I didn't want to clutter up the question with unnecessary info. models.py: class StoreNightlyReportsBase(models.Model): store_nightly_report = models.ForeignKey(StoreNightlyReport) no_new_item = models.BooleanField(verbose_name="Check if No New Items", default=False) customer = models.CharField(verbose_name='Customer Name', max_length=20, null=True, blank=True) class Meta: abstract = True permissions = (('nightly_reports','Nightly Reports'), ) class StoreNightlyReportsNewLoan(StoreNightlyReportsBase): ... class StoreNightlyReportsRenewals(StoreNightlyReportsBase): ... views.py class StoresNightlyReportsNewLoansCreate(CreateView): ... def get_form(self, form_class=None): ... def get_context_data(self, **kwargs): ... def form_valid(self, form): ... perm = Permission.objects.filter(codename='nightly_reports') users = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm)).distinct() recipients = list(i for i in users.values_list('email', flat=True) if bool(i)) html_email = … -
Adding a sitemap to Django 1.10.7
I'm having issues getting the Django setup to generate a sitemap for me. I have added the following to my settings file 'django.contrib.sites', 'django.contrib.sitemaps', and in my urls file I have the following: from django.conf.urls import include, url from django.contrib import admin from ames import views from cms.sitemaps import CMSSitemap admin.autodiscover() urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^contact/', include('contact.urls')), url(r'^news/', include('news.urls')), url(r'^sitemap.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^$', views.home), url(r'^', include('cms.urls')), ] When deploying these amends I get the following error on the site: TypeError at /sitemap.xml/ view must be a callable or a list/tuple in the case of include(). Any thoughts would be most welcome. -
How to login using the Mobile Number in Django Rest Framework.
We are using the django rest framework, for the login module, with the phone number. To authenticate the same, I want to use the OTP(One Time Password). How this can be achieved. This can be done using the auth-token of rest framework. But that it doesn't seem to be a good idea. Any other approach. Please help. -
How to create a confirmation popup for class.DeleteView
I am looking to create a confirmation popup window whenever the delete button is clicked. It currently is functional and immediately deletes. Here is some of my code: views.py: class patientDelete(LoginRequiredMixin, DeleteView): model = patient success_url = reverse_lazy('patients:index') index.html <form action="{% url 'patients:patient-delete' patient.id %}" method="post" style="display: inline;"> {% csrf_token %} <input type="hidden" name="patient_id" value="{{ patient.id }}" /> <button type="submit" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-trash"></span> </button> </form> and my urls.py # /patients/patient/pk/delete url(r'patient/(?P<pk>[0-9]+)/delete/$', views.patientDelete.as_view(), name='patient-delete'), I have searched left, right and center and dont really understand most of it. I have been using a lot of tutorials to help me here and am quite new to django. Thanks for your help in advance! -
Returning Only ID list, Want more data in Onclick
I am using AnyCluster/Django When I click on Markers, a Popup is open and only ID is appears on it, I want more details like name,city etc. at PopUp page What code i use is : # return all IDs of the pins contained by a cluster def getClusterContent(self, custom_filterstring=""): x = self.params["x"] y = self.params["y"] cluster = Point(x, y, srid=self.input_srid) # request lnglat point cell_geos = self.maptools.getCellForPointAsGeos(cluster, self.zoom, self.gridSize, self.db_srid) cluster.transform(self.db_srid) query_geometry = None for geometry in self.cache["geometries"]: geos = GEOSGeometry(geometry) if cluster.within(geos): query_geometry = geos.intersection(cell_geos) break filterstring = self.constructFilterstring(json.loads(self.cache["filters"])) filterstring += custom_filterstring kmeans_list = self.params["ids"] kmeans_string = (",").join(str(k) for k in kmeans_list) entries_queryset = Gis.objects.raw(''' SELECT * FROM ( SELECT kmeans(ARRAY[ST_X(%s), ST_Y(%s)], %s) OVER () AS kmeans, "%s".* FROM "%s" WHERE %s IS NOT NULL AND ST_Intersects(%s, ST_GeometryFromText('%s', %s) ) %s ) AS ksub WHERE kmeans IN (%s) ''' %(geo_column_str, geo_column_str, BASE_K, geo_table, geo_table, geo_column_str, geo_column_str, query_geometry.ewkt, self.db_srid, filterstring, kmeans_string )) return entries_queryset Thanks in Advance -
Passing value from template to django view
I have a template in which I display some values. Now I want to be able to change that values. So I have an input field with the value "capacity.capacity". The user can now change this value in the input field and click on button "Change". Now I want to process the newly entered value in my django view. How can I pass the new value to my view? I tried to add the value in the url so that I can retrieve it in my view again. Is it possible to add the new value to the url? <td> <input type="number" name=new_capacity id="new_capacity" step="1" value= {{ capacity.capacity }} > <button> <span class="glyphicon glyphicon-edit"></span><a href="{% url 'change_capacity' item_id=capacity.pk new_capa=NEWVALUE %}"> Change</button> </td> -
Javascript heap out of memory
I am getting the following error while using npm start for my angular pages. C:\TPO\Client\Angular>ng serve Your global Angular CLI version (1.3.2) is greater than your local version (1.0.4). The local Angular CLI version is used. To disable this warning use "ng set --global warnings.versionMismatch=false". ** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 ** 10% building modules 4/4 modules 0 active <--- Last few GCs ---> 118169 ms: Mark-sweep 1348.4 (1404.3) -> 1348.1 (1404.3) MB, 1338.9 / 0.0 ms [allocation failure] [GC in old space requested]. 119374 ms: Mark-sweep 1348.1 (1404.3) -> 1348.1 (1404.3) MB, 1204.7 / 0.0 ms [allocation failure] [GC in old space requested]. 121097 ms: Mark-sweep 1348.1 (1404.3) -> 1362.7 (1403.3) MB, 1723.2 / 0.0 ms [last resort gc]. 122416 ms: Mark-sweep 1362.7 (1403.3) -> 1377.4 (1403.3) MB, 1317.9 / 0.0 ms [last resort gc]. <--- JS stacktrace ---> ==== JS stack trace ========================================= Security context: 0000034B7C13FA99 1: set [native collection.js:~252] [pc=00000174AF1BC2E1] (this=000003AD36FBC469 ,r=000002D7A3418CD9 ,z=1) 2: /* anonymous */ [C:\TPO\Client\Angular\node_modules\typescript\lib\typescript.js:~2177] [pc=00000174ADC9EBD0] (this=000001D0EA536CE1 ,value=1,key=000002D7A3418CD9 ) 3: arg... FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory -
How to check if a value in exists in a column of cache query in django?
I am writing a django application where I create a model object and then bulk create data in the end. Here is my code: date_list = [list of dates] data = [] for date in date_list: if not date in data: data.append(Model2(date = date)) Model2.objects.bulk_create(data) This is where the error is: if not date in data: How do I search for object with my date in a list which looks like: [ Model2(date = date), Model2(date = date), Model2(date = date),..] Any suggestions? -
Django static files not loading in production
I always get 404 error in loading static files in an EC2 instance. I have searched for hours and tried to implement various suggestions but nothing worked. Following is my configuration of different files: settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') LOGIN_REDIRECT_URL = '/' html {% extends "base.html" %} {% load staticfiles %} {% block extra_head %} <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.css"> <script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.js"></script> <script src="{% **static "ddv_example/ddv_example_1_10.js"** %}"></script> <script type="text/javascript"> nginx.conf location /static/admin { alias /usr/local/virtualenvs/mysite/lib/python2.7/site-packages/django/contrib/admin/static/admin; } location /static/rest_framework { alias /usr/local/virtualenvs/mysite/lib/python2.7/site-packages/rest_framework/static/rest_framework; } location /static { alias /usr/local/apps/mysite/src/mysite/mysite/static; } location /static/ddv_example { alias /usr/local/apps/mysite/src/mysite/mysite/static/ddv_example; } Any suggestions on what am i missing out ? -
Increase the size of data sent through HTTP POST request in Djano
I want to send around 3MB of data using HTTP POST request in Django to a server. I am setting stream=True while sending the request. Is there any other way that I should try to increase the size of the data I am sending? It is not a file post request. -
Celery: Numerous small tasks or one long running task?
I have a Django app and using Celery to process long running tasks. Let's say I need to generate a file (takes 5 seconds), attach it to an email and send it to 1000 users, which of these methods are the preferred way? Method 1: For loop outside task - generates numerates background tasks, each running a couple of seconds @share_task def my_task(usr): #gen file + send email... def send_to_all_users(users): # called to start task for usr in users: my_task.delay(usr) Method 2: For loop inside task - generates 1 background tasks that could be running for hours @share_task def my_task(users): for usr in users: #gen file + send email... def send_to_all_users(users): # called to start task my_task.delay(users) With method 1, I can scale up the number of workers to complete the entire task quicker, but creating all those tasks might take a while and I'm not sure if my task queue can fill up and then jobs get discarded? Method 2 seems simpler, but it might run a very long time and I can't scale up the number of workers. Not sure if it matters, but my app is running on Heroku and I'm using Redis as the message broker. … -
Restrict access with middleware
According to this solution: https://stackoverflow.com/a/44208282/2950384 you are suppose to restrict acccess to whole website with exceptions. I have put this code in a middleware.py file and under my login app. Also added it to settings.py - MIDDLEWARE at the bottom. middleware.py from django.contrib.auth.decorators import login_required from django.urls import reverse def login_required_middleware(get_response): """ Require user to be logged in for all views. """ exceptions = {'/admin/login/'} def middleware(request): if request.path in exceptions: return get_response(request) return login_required(get_response, login_url=reverse('admin:login'))(request) return middleware Settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'login.middleware.login_required_middleware', ] But this makes nothing to my website. I still can access all without being logged in. -
Django Rest Framework model serializer with out unique together validation
I have a model with some fields and a unique together: .... class Meta(object): unique_together = ('device_identifier', 'device_platform',) Obviously, in this way, about Django rest framework serializer, I obtain an error when I try to make a PUT with the same device_identifier and device_platform (if already exist an entry with this data). { "non_field_errors": [ "The fields device_identifier, device_platform must make a unique set." ] } Is possible to disable this validation in my model serializer? Because I need to manage this situation during save model step (for me, in serializer validation this is not an error) -
How to pick only one row from rows with common date in datetimefield?
I am writing a django application where I have to pick only one row from and exclude the rest of them from multiple rows containing same date in their datetimefield column. My model is: class Model(models.Model): user_id = models.IntegerField() datetime = models.DateTimeField() I want to select only one user from each single date. Here is how i select all rows: data = Model.objects.all() How do I select only one user from each date in datetimefield? -
Data not shown in Django admin after adding by my form
I am a beginner to Django. I want to create a form that allow user to store their data to the database, but I face to an issue. If I add data through Django admin, the data will shown correctly. But if I add data through my form. Data will store into database successfully but they don't shown in my Django admin. Note: The Django version I used is 1.11.2 The is my Django admin page. There are 8 data in the database but just show the one I added by the Django admin. views.py from django.shortcuts import render from django.views.generic import CreateView from .forms import ApplyFormCreateForm from .models import ApplyForm class ApplyFormCreateView(CreateView): form_class = ApplyFormCreateForm template_name = 'form.html' success_url = "/" models.py from django.db import models from course.models import Semester DEFAULT_SEMESTER_ID = 1 class ApplyForm(models.Model): name = models.CharField(max_length=15) school = models.CharField(max_length=20) department = models.CharField(max_length=20) email = models.EmailField(max_length=100) is_beginner = models.BooleanField(default=False) introduction = models.TextField(max_length=2000) motivation = models.TextField(max_length=2000) comments = models.TextField(max_length=2000, blank=True) semester = models.ForeignKey(Semester, default=DEFAULT_SEMESTER_ID) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __unicode__(self): return self.school + self.department + self.name def __str__(self): return self.school + self.department + self.name form.html {% extends "base.html" %} {% block content %} <form method='POST'> {% csrf_token … -
Empty Search Results in Haystack Solr Django (Getting Output with prefix u in Django Shell)
Start a Django shell (./manage.py shell) from haystack.query import SearchQuerySet sqs = SearchQuerySet().all() sqs.count() // get back an integer > 0 (Output is 1800) But when i use sqs[0].text Result is : u"[u'PALMER SECOND BAPTIST CHURCH\\nPALMER\\n']" An extra u"[u' as a prefix appears in my output ! I think because of this my Search Results is Empty Already Follow https://django-haystack.readthedocs.io/en/latest/debugging.html for Debugging Thanks in Advance for any help to solve this issue -
Count number of records by date
Given this model: Foo(models.Model): some_fields ... date = models.DateTimeField(db_index=True, auto_now_add=True) I want to show the data in a graph where X axis is time (HH:MM) and Y axis is the number of instances at that time. I've tried this: Foo.objects.extra({'date_created' : "date(date)"}).annotate(created_count=Count('id')).values('date_created', 'created_count') But the value of created_count is always 1, even if I create 2 instances at the same time (bulk_create). Any idea to accomplish this in Django 1.8? -
Generated django queryset works, but running it in django fails
I've tried replacing INNER_QUERY with "myApp_Instructionssteptranslation", and also leaving it away but this just gives other errors. So, how come the generated query seems to work correctly when ran apart, but fails when we want to retrieve its results using django? And how can I fix the issue so that it behaves like I want it too?We have a model InstructionsStep, which has a foreign key to a Instructions, which in turn is connected to a Library. A InstructionsStep has a description, but as multiple languages might exist this description is stored in a separate model containing a language code and the description translated in that language. But for performance reasons, we need to be able to get a queryset of Instructionssteps, where the description is annotated in the default language (which is stored in the Library). To achieve this and to circumvent django's limitations on joins within annotations, we created a custom Aggregate function that retrieves this language. (DefaultInstructionsStepTranslationDescription) class InstructionsStepTranslationQuerySet(models.query.QuerySet): def language(self, language): class DefaultInstructionsStepTranslationDescription(Aggregate): template = '(%(function)s %(distinct)s INNER_QUERY."%(expressions)s" FROM ('\ 'SELECT "myApp_Instructionssteptranslation"."description" AS "description", ' \ 'MIN("myUser_library"."default_language") AS "default_language"' \ 'FROM "myApp_Instructionssteptranslation" ' \ 'INNER JOIN "myApp_Instructionsstep" A_ST ON ("myApp_Instructionssteptranslation"."Instructions_step_id" = A_ST."id") ' \ 'INNER JOIN …