Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Failed to load resources in ajax
I'm trying to access some string from django models using ajax. I'm new to ajax and i don't know where I'm going wrong. Here is Jquery code :- $(document).ready(function () { $("input.ssd").click(function () { var lsid = $(this).attr("id"); lsid = Number(lsid); $.ajax({ type: "POST", url: "/a_solution/", data: { l_sid: lsid, }, success: console.log("success") datatype: 'html', error : console.log("oops! something went wrong"), }); }); }); Here is url mapping in urls.py : url(r'^a_solution/$', views.ajax_detail, name = 'ajax_detail'), Here is views code :- def ajax_detail(request): context = {} if request.method == "POST" : l_sid = request.POST["l_sid"] else: ans = 'Oops! something went wrong' context['ans'] = ans l_sid = int(l_sid) sid = l_sid % 10 lid = l_sid // 10 solution = Solution.objects.get(id = sid) for code in solution.code_set.all : if code.language.id == lid: ans = code.source_code context['ans'] = ans break return render(request,'program/solution_detail.html',context) -
Django-q with Amazon SQS configuration
I've been trying to configure Django-q for the first time, with Amazon SQS as a broker. I'm using Python 2.7.11, Django 1.11.5, Django-q 0.9.2, boto3 1.5.28 and django-storages 1.4.1. I've been already using AWS S3 and cloudfront in my Django app for a few years, so they are configured properly. I'm using S3 and cloudfront for serving media files, while django-whitenoise for serving django static files. I've created new IAM user just for SQS and gave it AmazonSQSFullAccess. List of apps im using in my project (settings.py): INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.humanize', 'django.contrib.sitemaps', 'utils', 'storages', 'my_app', 'debug_toolbar', 'widget_tweaks', 'django_q', ) Following the Django-q documentation, i've come up to the step where i should execute this command python manage.py qcluster which gives me these errors: pickle.PicklingError: Can't pickle <class 'boto3.resources.factory.sqs.ServiceResource'> it's not found as boto3.resources.factory.sqs.ServiceResource and Django error as well: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. which leaves me confused, i really have no idea what could be the problem.. -
Run simultaneously UWSGI and ASGI with Django
I'm currently running a Django (2.0.2) server with uWSGI having 10 workers I'm trying to implement a real time chat and I took a look at Channel. The documentation mentions that the server needs to be run with Daphne, and Daphne needs an asynchronous version of UWSGI named ASGI. I manged to install and setup ASGI and then run the server with daphne but with only one worker (a limitation of ASGI as I understood) but the load it too high for the worker. Is it possible to run the server with uWSGI with 10 workers to reply to HTTP/HTTPS requests and use ASGI/Daphne for WS/WSS (WebSocket) requests ? Or maybe it's possible to run multiples instances of ASGI ? -
How to access cleaned data in a Django form's clean() method?
I'd like to implement an input field in a Django form, phone_type, which is only required when another field, phone_number, is filled in. I'm reading the example at https://www.fusionbox.com/blog/detail/creating-conditionally-required-fields-in-django-forms/577/ on how to do this: def clean(self): shipping = self.cleaned_data.get('shipping') if shipping: msg = forms.ValidationError("This field is required.") self.add_error('shipping_destination', msg) else: # Keep the database consistent. The user may have # submitted a shipping_destination even if shipping # was not selected self.cleaned_data['shipping_destination'] = '' return self.cleaned_data where the models are defined as from django.db import models class ShippingInfo(models.Model): SHIPPING_DESTINATION_CHOICES = ( ('residential', "Residential"), ('commercial', "Commercial"), ) shipping = models.BooleanField() shipping_destination = models.CharField( max_length=15, choices=SHIPPING_DESTINATION_CHOICES, blank=True ) When comparing this code to the documentation at https://docs.djangoproject.com/en/2.0/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other, however, I notice that there is no call to super().clean(). Instead of accessing self.cleaned_data directly, should I do cleaned_data = super().clean() shipping = cleaned_data.get('shipping') in the first lines of the custom clean() method? (I would also be interested in ways to make the field conditionally visible without requiring additional jQuery/JavaScript code, e.g. using Django Crispy Forms and/or the HiddenInput widget). -
How do you get the JSON payload from django request object?
I'm making a post request that looks like so: $.post('/api/somepath/' {'containers': [{'container_type':'alert', 'id':1}....]}) And in my django views, self.request.POST shows the following: <QueryDict: {u'containers[1][container_type]': [u'alert'], u'containers[1][id]': [u'12159'], u'containers[0][id]': [u'9703'], u'containers[0][container_type]': [u'alert']}> How do I retrieve it back as a list? I've tried: self.request.POST.getlist('containers[]') but this returns an empty list -
Django TabularInline and formfield_for_manytomany
I try to filter results showed in a ManyToManyField, in admin. I use Django 1.11.3. I have these two models: class Data(models.Model): data_id = models.AutoField(primary_key=True) fi_id = models.IntegerField() model_name = models.CharField(max_length=255) def __str__(self): return self.model_name class Car(models.Model): fi_id = models.IntegerField() data = models.ManyToManyField(Data) def __str__(self): return str(self.fi_id) and this code in my admin.py file: admin.site.register(Data) class DataInline(admin.TabularInline): model = Car.data.through extra = 1 class CarAdmin(admin.ModelAdmin): inlines = [DataInline,] def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "data": kwargs["queryset"] = Data.objects.filter(fi_id=request.GET.get('fi_id')) return super(CarAdmin, self).formfield_for_manytomany(db_field, request, **kwargs) admin.site.register(Car, CarAdmin) I added this line return db_field.formfield(**kwargs) after kwargs["queryset"], but no luck. Code works, but not for the inline section. I attached a photo. -
ModelForm __init__ being called a ridiculous amount of times
Just going to put some code and explain at the bottom. # modelforms.py # class MyModelModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(MyModelModelForm, self).__init__(*args, **kwargs) print '__init__' class Meta: model = MyModel exclude = ('my_fk', ) Here I am using django-vanilla-views # views.py # class MyCreateView(NoAdminNoStaffLoginRequiredMixin, HasPermissionsMixin, CreateView): template_name = 'modelform_create.html' form_class = MyOtherModelModelForm # this modelform isn't important required_permission = 'create_model' def get_success_url(self): return reverse_lazy('mymodel_detail', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super(MyCreateView, self).get_context_data(**kwargs) # FIXME: form's __init__ being called a lot MyModelFormset = modelformset_factory( MyModel, form=MyModelModelForm, extra=4, max_num=10, validate_max=True) if self.request.POST: formset = MyModelFormset( self.request.POST, queryset=MyModel.objects.none(), form_kwargs={'request': self.request}) else: formset = MyModelFormset( queryset=MyModel.objects.none(), form_kwargs={'request': self.request}) print formset.total_form_count() # 4, which makes sense context['formset'] = formset return context MyModelModelForm __init__ gets called 18 times. Yeah, I was wondering if I could get that from not happening. Reason being I would like it to not be called multiple times is I query the DB for forms.ChoiceField(choices=...), which queries the DB that many times unnecessarily. Or if there is a better spot for populating choices (NOTE: I cannot just do it in the same space where the field is declared.) It is a mixin that populates this certain field. … -
How to substitute a query value into a command argument
I need to call a shell process but pass a value in from a database query for the fourth argument, I've tried everything under the sun to get this to work including using % and {{ etc: stream1 = subprocess.check_output(['command','xxxx','yyyy','zzz','document.document_id']) Any help would be much appreciated, I've spent all afternoon trying to google the solution but I have a feeling I am phrasing the question wrongly. -
issues with Django Passing Data from Template to View url dispatch
Having the below error while trying to dispatch two variables from my template to my view via url dispatching. I dont understand why the url is not able to be found. NoReverseMatch at /home/patientid=1002411102/clinicid=1007/ Reverse for 'patient_summary' with no arguments not found. 1 pattern(s) tried: ['home/patientid=(?P<patient_id>\\d+)/clinicid=(?P<clinic_id>\\d+)/$'] index.html <tbody> {% for patient in patients %} <tr class="gradeX"> <td>{{patient.PatientID}}</td> <td>{{patient.ClinicID}}</td> <td>{{patient.PatientFirstName}}</td> <td>{{patient.PatientMidName}}</td> <td>{{patient.PatientLastName}}</td> <td>{{patient.PatientDOB}}</td> <td>40/30</td> <td>192</td> <td>100</td> <td>70</td> <td>23m</td> <td style="color:red">Abnormal</td> <td><a style="color:#4A90E2; cursor: pointer" href="{% url 'home:patient_summary' patient_id=patient.PatientID clinic_id=patient.ClinicID %}">View/Edit</a></td> </tr> {% endfor %} </tbody> urls.py from django.conf.urls import url from home import views app_name = 'home' urlpatterns = [ url('^$', views.index, name='index'), url('patientid=(?P<patient_id>\d+)/clinicid=(?P<clinic_id>\d+)/$', views.patient_summary, name='patient_summary'), ] views.py def patient_summary(request, patient_id, clinic_id): my_dict = {'homeIsActive': 'active', 'chartData': [[0,1],[1,1],[2,1]]} return render(request, 'home/patient_summary.html', my_dict) -
Get HttpUnauthorized error Tastypie Unittest with ResourceTestCaseMixin
I am following: http://django-tastypie.readthedocs.io/en/latest/testing.html to write REST API unittest for Django project implemented with Tastypie. The unittest is to trigger validation code in HelloValidation class. Here is partial code: ===>rest_api.py from tastypie import validation from tastypie import resources class HelloValidation(Validation): def is_valid(self, bundle, request=None): """Unittest to test code HERE!!!""" class HelloResource(ModelResource): """Represent lab object type resource.""" class Meta(object): validation = HelloValidation() ===>RESTapiUnittest.py from myproject.rest_api import rest_api from tastypie.test import ResourceTestCaseMixin class MyTestCase(TestCase): def setUp(self): management.call_command('flush', interactive=False) self.InitializeDB() # It create temporary database in sqlite. self.post_header = {} self.rest_url = '/api/v1/hello/' def tearDown(self): pass class HelloRestAPITest(ResourceTestCaseMixin, MyTestCase): status = self.api_client.get(self.rest_url, format='json', data=self.header_data, validation=rest_api.HelloValidation()) But, I got error and validation code is not triggered. Why? What's missing? HttpUnauthorized: Vary: Cookie Content-Type: text/html; charset=utf-8 X-Frame-Options: SAMEORIGIN Content-Length: 0 -
How do I get data from my AJAX Post to my Django View?
This is what My ajax call looks like $.ajax({ url:"/utility_tool/decisions/solution_options/handsontable.html", data: {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value, getdata: JSON.stringify(hot.getData())}, dataType: 'json', type: 'POST', success: function (res) { alert(data); alert(res.status); }, error: function (res) { alert(res.status); } }); The alert for data displays correctly but alert for res.status displays "undefined". This is what my django view looks like. if request.method == 'POST': request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') request_getdata = request.POST.get('getdata', '') return HttpResponse(request_getdata) If I do HttpResponse of csrf_token, it displays the correct value. But when I do HttpResponse of getdata, it does not display anything. Any help would be much appreciated. -
Possible to get documentation for model properties in django.contrib.admindocs?
Is it possible to have model properties (like the following) show up in the admin documentation using django.contrib.admindocs? class MyModel(models.Model): name = models.CharField(max_length=200) public = models.BooleanField(default=False) date_approved = models.DateTimeField(null=True, blank=True) @property def status(self): """ returns the status of object """ if self.date_approved and self.public: return "Public" elif self.public: return "Pending Approval" else: return "Private" -
Django pagination not working as intended, page numbers and links rendered wrong
I have four models: faculties, departments, studies and courses, all bound by a foreign key hierarchically. And I have a web page that is divided in two columns. First column contains a way to display the courses in my second column. By default, in the second column all courses are shown and by using first column filters, I can display those courses by faculty or by study programme. I set up pagination for all courses which works, but if I decide to sort courses by faculty for example, the number of the course object that gets shown, coincides with the default courses page number. And if I try to access another page number, it will redirect me to the specific page of the default courses. https://i.imgur.com/ucMgwlW.png <script> $(document).ready(function () { $('.btnClick').on('click', function () { $('.col-md-9').find('[id^="dep"]').hide(); var faculty_id = $(this).attr('id'); $('#' + faculty_id + '_tab').show().siblings('div').hide(); }); $('.btnClick2').on('click', function () { $('.col-md-9').find('[id^="std"]').hide(); var study_id = $(this).attr('id'); $('#' + study_id + '_tab').show().siblings('div').hide(); }); $('.btnClick3').on('click', function () { var a = $('.col-md-9'); a.find('[id^="fac"]').hide(); a.find('[id^="std"]').hide(); a.find('[id^="crs"]').show(); }); }); </script> <div class="row"> <div class="col-md-3"> <div class="jumbotron"> <h4>Search courses</h4> <hr> <br> <p onClick="window.location.reload()" class="btnClick3">Show all courses</p> <br> <ul> {% for faculty in faculties %} <li class="btnClick" id="fac_{{ … -
Django Filtering results inside ManyToManyField
I need to filter the results of a ManyToManyField before serializing it. Example: A user should see details on a record only if 'expiration_date' hasn't passed for 'Authorized Program' on file for the 'Individual' who is the subject of the record. My model and serializer currently show a list of ALL related Authorized Program records. Question: How can I filter that list to only non-expired records before returning as a list in the parent 'individual' record? Note: This is not a question about filtering the parent queryset based on the M2M field. It's about filtering the contents of the M2M field before returning the parent. Currently, the serializer simply skips the 'active_authorized_program_list' field. class Individual(models.Model): name = models.CharField(max_length=128, blank=True, default='') dob = models.DateField(null=True) authorized_program_list = models.ManyToManyField( 'Program', related_name='individual_authorized_program_list', through='ReleaseAuthorization', blank=True ) @property def current_age(self): if self.dob: today = datetime.date.today() return (today.year - self.dob.year) - int( (today.month, today.day) < (self.dob.month, self.dob.day)) else: return 'Unknown' @property def active_authorized_program_list(self): return ( self .authorized_program_list .get_queryset() .filter(expiration_date__lte=datetime.Date()) ) class Program(models.Model): name = models.CharField(max_length=128, blank=True, default='') individual_list = models.ManyToManyField( 'individual.Individual', related_name='program_individual_list', through='hub_program.ReleaseAuthorization', blank=True ) active = models.BooleanField(default=True) class ReleaseAuthorization(models.Model): individual = models.ForeignKey( Individual, related_name="release_authorization_individual", on_delete=models.CASCADE ) program = models.ForeignKey( Program, related_name="release_authorization_program", on_delete=models.CASCADE ) expiration_date = models.DateField() … -
in account_activation_email.html add href doesnt display correct
I want to add hyperlink to account_activation_email.html {% load staticfiles %} {% load i18n %} {% autoescape off %} {% trans 'Hi' %} {{ user.username }}, {% trans 'Please click on the link below to confirm your registration' %}: <a href="http://{{ domain }}{% url 'activate' uidb64=uid token=token %}"> </a> {% endautoescape %} but in the mail I see it as follow what am I doing wrong? -
Sending multiple sms in quick succession using Twilio
I am trying to send sms using twilio and django 1.8.2. I am facing a problem when there are multiple calls to send sms within the same function. This is the code snippet to send an sms to any particular phone number: def send_twilio_message(to_number, body): client = twilio.rest.TwilioRestClient( settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) return client.messages.create( body=body, to=to_number, from_=settings.TWILIO_PHONE_NUMBER ) When I make two requests to this function like this: def some_function(): send_twilio_message(number1, "text 1") send_twilio_message(number2, "text 2") I am getting this error: Traceback: File "/home/arka/Project/TreadWill/env/lib/python3.5/site- packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/arka/Project/TreadWill/dreamhost/CCBT/trial_IITK/views.py" in waitlist_phq 782. exclusion_code = waitlist_alert(wl.participant, phq_score) File "/home/arka/Project/TreadWill/dreamhost/CCBT/trial_IITK/views.py" in waitlist_alert 857. send_twilio_message(phonenumber, 'Looks like your child maybe having suicidal thoughts. Get in touch with your child ASAP. - TreadWill.') File "/home/arka/Project/TreadWill/dreamhost/CCBT/sendsms/utils.py" in send_twilio_message 13. from_=settings.TWILIO_PHONE_NUMBER File "/home/arka/Project/TreadWill/env/lib/python3.5/site- packages/twilio/rest/resources/messages.py" in create 122. return self.create_instance(kwargs) File "/home/arka/Project/TreadWill/env/lib/python3.5/site- packages/twilio/rest/resources/base.py" in create_instance 365. data=transform_params(body)) File "/home/arka/Project/TreadWill/env/lib/python3.5/site- packages/twilio/rest/resources/base.py" in request 200. resp = make_twilio_request(method, uri, auth=self.auth, **kwargs) File "/home/arka/Project/TreadWill/env/lib/python3.5/site- packages/twilio/rest/resources/base.py" in make_twilio_request 152. resp = make_request(method, uri, **kwargs) File "/home/arka/Project/TreadWill/env/lib/python3.5/site- packages/twilio/rest/resources/base.py" in make_request 117. resp, content = http.request(url, method, headers=headers, body=data) File "/home/arka/Project/TreadWill/env/lib/python3.5/site- packages/httplib2/__init__.py" in request 1314. (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) File "/home/arka/Project/TreadWill/env/lib/python3.5/site- … -
Django Model Field Auto-Updates Depending on Related Instances
I am looking for a solution to being able to automatically update model instances depending on a related model instance. It seems simple and I've looked everywhere. I'm new to this so let me know I am asking the question incorrectly or thinking about it in the wrong way. I need Account.monthly_donations to automatically update to the total amount of all of it's related donations in the last 30 days. Similarly for yearly_donations and lifetime_donations. I also need Account.is_subscribed to toggle True if monthly_donations >= 20, or yearly_donations >= 200 or lifetime_donations >= 10000 and then back to False if requirements not met. class Account(models.Model): ... is_subscribed = models.BooleanField( default=False ) monthly_donations = models.PositiveIntegerField( default=0 ) yearly_donations = models.PositiveIntegerField( default=0 ) lifetime_donations = models.PositiveIntegerField( default=0 ) class Donation(models.Model): related_account = models.ForeignKey( Account, on_delete=models.CASCADE, related_name='donation' ) amount = models.IntegerField() date = models.DateField() Are signals the solution? However, I don't want the totals to update only when a new donation is saved. I need it updated daily based on the donations dates. -
Django 1.11.6: 'str' object has no attribute 'payment_method'
I'm writing valid inputs into a form so I can save it into my database, however, it will not save because of the following error: Traceback C:\Python34\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) ... C:\Python34\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) C:\Python34\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) G:\NEA Computer Science\mysite\finance\views.py in record_input if form.is_valid(): # check whether it's valid C:\Python34\lib\site-packages\django\forms\forms.py in is_valid return self.is_bound and not self.errors C:\Python34\lib\site-packages\django\forms\forms.py in errors self.full_clean() C:\Python34\lib\site-packages\django\forms\forms.py in full_clean self._post_clean() C:\Python34\lib\site-packages\django\forms\models.py in _post_clean self.instance.full_clean(exclude=exclude, validate_unique=False) C:\Python34\lib\site-packages\django\db\models\base.py in full_clean self.clean_fields(exclude=exclude) C:\Python34\lib\site-packages\django\db\models\base.py in clean_fields setattr(self, f.attname, f.clean(raw_value, self)) C:\Python34\lib\site-packages\django\db\models\fields__init__.py in clean self.run_validators(value) C:\Python34\lib\site-packages\django\db\models\fields__init__.py in run_validators v(value) G:\NEA Computer Science\mysite\finance\models.py in validate_pay_method if self.payment_method != "Cash" and self.list_price == self.deposit: AttributeError: 'str' object has no attribute 'payment_method' I think this is something to do with PAYMENT_CHOICES and the type of value it is, but I cannot think about how to go about it. Thank you! Code: views.py from django.http import HttpResponse from django.shortcuts import render, redirect from .models import Customer, Dealer from .forms import CustomerForm import datetime # Lists all dealers and links them to their welcome page def index(request): dealer_list = Dealer.objects.order_by('name') html = "<ol>" for dealer in dealer_list: html += "<li><a href='"+str(dealer.id)+"/'>"+dealer.name+"</a></li>" html += "</ol>" … -
Django Apache MsSQL connection timeout
I am trying to Django with mssql on CentOs7 using Apache Mod_wsgi. I'm able to run the Django app using python manage.py runserver 0.0.0.0:8000 and navigate to my grappeli admin page. However, when I run using Apache, the home site loads up just fine but then I get OperationalError: ('HYT00', u'[HYT00] [unixODBC][Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') when I attempt to navigate to the admin page. It's strange that runserver would work using the same virtualenv that I'm pointing my apache config at. pip freeze: Django==1.11.10 django-grappelli==2.10.2 django-pyodbc==1.1.3 django-pyodbc-azure==1.11.9.0 pymssql==2.1.3 pyodbc==4.0.22 contents of /etc/httpd/conf.d/django.conf: <Directory /opt/measurement_app/measurement_app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess measurement_app python-path=/opt/measurement_app:/opt/measurement_app/measurementenv/lib/python2.7/site-packages WSGIProcessGroup measurement_app WSGIScriptAlias / /opt/measurement_app/measurement_app/wsgi.py settings.py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'MEASUREMENT', 'HOST': ****, 'PORT': 1433, 'USER': ****, 'PASSWORD': *****, 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'dsn': 'app-sqldb', 'use_legacy_datetime': True, } } } odbcinst.ini [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server Driver=/opt/microsoft/msodbcsql/lib64/libmsodbcsql-17.0.so.1.1 UsageCount=1 odbc.ini [app-sqldb] Driver = ODBC Driver 17 for SQL Server Description = SQL Server 2012 DenSQL Server = **** instance = MEASUREMENT Database = MEASUREMENT Port = 1433 Trace = Yes TraceFile = /tmp/odbc.log -
Python using xhtml2pdf in django to print html into PDF
I am using this basic example to generate a pdf, but now I want to obtain a template that I also generate with xhtml2pdf Example Basic How can I get the template ? I tried with this: template = get_template('mytemplate.html') sourceHtml = template outputFilename = "test.pdf" error -
Overlay using Django and Bootstrap dropdown menu
I'm trying to create an overlay that overlays a page with a spinner in the middle. So, when a user select something from a drop-down menu, I want to have this overlay during the loading state. I found a lot of questions about this topic but none explains the mechanism. Does anybody explain how I can implement that using Django and Bootstrap? Do you have an example? Many thanks in advance for your help. Gilles -
Django - Generic Detail View must be called with either an object pk or slug
I have searched through other questions regarding the same error message, but it seems as if it should work to me (I am using Django 2 btw.) class Book(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(default='') def save(self, *args, **kwargs): self.slug = self.name.lower().replace(' ', '_') my path: path('<slug:slug>', views.BookDetailView.as_view(), name='book-detail'), the view: class BookDetailView(DetailView): model = Book template_name = 'books/bookdetail.html' context_object_name = 'book' slug_url_kwarg = 'slug' Still, it's throwing the error message. What have I done wrong? Thanks in Advance -
Django - all objects from last hour
I would like to get all objects from last hour. For example: I have 13:58 and i would like to get all objects from 13 to 14 This is my code: now = datetime.datetime.now() earlier = now - datetime.datetime(now.year, now.month, now.day, now.hour, 0,0) MyModel.objects.filter(date__range=(earlier, now)) but I have a error: RuntimeWarning: DateTimeField MyModel.date received a naive datetime (2018-02-14 17:16:58.478000) while time zone support is active. RuntimeWarning) My settings: USE_TZ = True TIME_ZONE = 'Europe/Warsaw' -
Django tests - database constraint still exists even with a migration
I'm having difficulty with migrations/constraints in tests. I started with something like this: class MyModel(AbstractModelWithoutCSlug): id = models.IntegerField(primary_key=True, db_column='other_id') cslug = models.CharField(max_length=60, null=True, unique=True) This created the unique constraint on cslug without an issue. The unique=True was removed on the field (and made the migrations) to allow a command to run that would require the ability to temporarily have non-unique values. When I run the tests, I get an IntegrityError on the lack of uniqueness, even though a migration exists removing unique=True. Is it possible the migrations aren't always done in tests? I've never encountered an issue with migrations not being run before. Additionally: I'm using factory boy for the models. Could this also have an effect on it? -
Is it possible to add another class to a django-bootstrap-ui template tag
In my django project, I'm using django-bootstrap-ui 0.5.1. I have it in my settings.py INSTALLED_APPS variable, as well as installed in my virtual environment via my requirements.txt file. I've confirmed everything is working by using a basic {% container %} tag and its child tags {% row %} and {% column xs="8" sm="6" md="4" lg="3" %}, for example. My question is this: If {% container %} renders the following code: <div class='container'> </div> How can I add another class to that div, alongside 'container', so that the output looks like: <div class='container custom-class'> </div>