Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create own data set to implement search functionality?
I am using sci kit learn with Django framework. I have loaded basic iris data set and checked all demo's provided. Now I want to create my own dataset with inputs and possible outputs. Can some one show me a demo of custom dataset? -
Range Slider with Dynamic max Value and scale
I am designing a Visualization Tool using Django. In UI, I need a range Slider to select values. The max Value of range Slider changes when page loads for the first time. How do i achieve this. I also want the scale of the slider along with min Value, max Value and current Value in a tool tip to be shown. Exactly Like this -
django : The included URLconf 'DB_query.urls' does not appear to have any patterns in it
I am very new to django and I'm having trouble running the manage.py script. My project is called DB_query. This is what I do : I run ./manage.py makemigrations This is the error I get : /home/ec2-user/atlas_web/atlas_web/local/lib/python2.7/site- packages/pkg_resources/__init__.py:1222: UserWarning: /home/ec2-user/.python-eggs is writable by group/others and vulnerable to attack when used with get_resource_filename. Consider a more secure location (set with .set_extraction_path or the PYTHON_EGG_CACHE environment variable). warnings.warn(msg, UserWarning) /home/ec2-user/atlas_web/atlas_web/local/lib/python2.7/site-packages/pkg_resources/__init__.py:1222: UserWarning: /home/ec2-user/.python-eggs is writable by group/others and vulnerable to attack when used with get_resource_filename. Consider a more secure location (set with .set_extraction_path or the PYTHON_EGG_CACHE environment variable). warnings.warn(msg, UserWarning) Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7f0d57fc4488> Traceback (most recent call last): File "/home/ec2-user/atlas_web/atlas_web/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/ec2-user/atlas_web/atlas_web/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/home/ec2-user/atlas_web/atlas_web/local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/home/ec2-user/atlas_web/atlas_web/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/home/ec2-user/atlas_web/atlas_web/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/ec2-user/atlas_web/atlas_web/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver for pattern in resolver.url_patterns: File "/home/ec2-user/atlas_web/atlas_web/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/ec2-user/atlas_web/atlas_web/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 426, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'DB_query.urls' does not appear to have any patterns in it. If you see … -
Restrict access to Nginx server which runs Token auth based Django rest framework.
Nginx provides auth_basic which makes use of HTTP_AUTHORIZATION header. Token authentication in DRF also uses HTTP_AUTHORIZATION . How to restrict access to the server in nginx level without modifying the codebase / DRF? -
i am redirected in login page and every time i click home or try to login i am redirected to login
i want to be redirected to home page when i open the system and how can i code my middleware.py to redirect me to home or to redirect a user to home page when he or she open the system.thank you this the respond from the development server [27/Mar/2017 12:59:28] "GET / HTTP/1.1" 302 0 account/login/ [27/Mar/2017 12:59:28] "GET /account/login/ HTTP/1.1" 200 5858 [27/Mar/2017 12:59:29] "GET / HTTP/1.1" 302 0 account/login/ [27/Mar/2017 12:59:29] "GET /account/login/ HTTP/1.1" 200 5858 [27/Mar/2017 12:59:29] "GET / HTTP/1.1" 302 0 account/login/ [27/Mar/2017 12:59:29] "GET /account/login/ HTTP/1.1" 200 5858 [27/Mar/2017 12:59:29] "GET / HTTP/1.1" 302 0 account/login/ [27/Mar/2017 12:59:29] "GET /account/login/ HTTP/1.1" 200 5858 [27/Mar/2017 12:59:30] "GET / HTTP/1.1" 302 0 account/login/ [27/Mar/2017 12:59:30] "GET /account/login/ HTTP/1.1" 200 5858 [27/Mar/2017 12:59:30] "GET / HTTP/1.1" 302 0 account/login/ [27/Mar/2017 12:59:30] "GET /account/login/ HTTP/1.1" 200 5858 [27/Mar/2017 12:59:30] "GET / HTTP/1.1" 302 0 account/login/ [27/Mar/2017 12:59:30] "GET /account/login/ HTTP/1.1" 200 5858 [27/Mar/2017 12:59:30] "GET / HTTP/1.1" 302 0 account/login/ [27/Mar/2017 12:59:30] "GET /account/login/ HTTP/1.1" 200 5858 this is my middleware.py import re from django.conf import settings from django.shortcuts import redirect EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: def __init__(self, get_response): … -
How to configure django-filer to use apache-libcloud as filer-server
The problem statement is this: In my django-based system, the staff members can upload videos, images etc. They can organized these files into folders. For this I am planning to use django-filer. As mentioned in their docs, by default django-filer uses a default filer-server. It stores the files in the same machine on which the server is hosted. But I want to use something like Apache libcloud so I can store these files on a different server than mine. I can sense that django-filer allows this because you can configure filer_storages but I am not able to figure out the configuration needed for Apache libcloud. What have I tried so far: I have mainly googled from different aspects like 'django-filer with apache libcloud' and 'upload files from django admin to apache libcloud'. But haven't found a solid lead yet. If any of you have done something like this before, you help would be much appreciated. TL;DR Need to upload files from django admin interface to different backend servers like ones supported by Apache Libcloud. Any help is much appreciated. -
How to get distance field in REST response?
I am using GeoDjango GIS for proximity search result based on latitude and longitude. The model, is quiet simple: class Address(gismodels.Model): # partner = models.ForeignKey(Partner, related_name="partner_addresses", on_delete=models.CASCADE) street = gismodels.CharField(max_length=255) city = gismodels.CharField(max_length=255) postcode = gismodels.CharField(max_length=255, null=True, blank=True, default='0000') country = gismodels.CharField(max_length=255) businesses = gismodels.OneToOneField(Business, related_name="business_address", on_delete=models.CASCADE, null=True) latitude = gismodels.FloatField(null=True, blank=True) longitude = gismodels.FloatField(null=True, blank=True) location = gismodels.PointField(null=True, blank=True) objects = gismodels.GeoManager() def __unicode__(self): return self.street class Meta: verbose_name = "Address" verbose_name_plural = "Addresses" def save(self, *args, **kwargs): if self.latitude and self.longitude: self.location = Point(self.longitude, self.latitude) super(Address, self).save(*args, **kwargs) And, so is the serializer: class AddressSerializer(HyperlinkedModelSerializer): name_of_business = serializers.CharField(source="businesses.name_of_business") business_id = serializers.IntegerField(source="businesses.pk") opening_time = serializers.TimeField(source="businesses.business_details.opening_time") class Meta: model = Address fields = ('pk', 'distance', 'street', 'city', 'postcode', 'name_of_business', "business_id", 'opening_time') So, when I try to get response, say using curl http://127.0.0.1:5000/api/businesses/37.4418834/-122.14301949999998/, I get this error related to the distance field: Traceback (most recent call last): File "/Users/nhst/.virtualenvs/gratis/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/Users/nhst/.virtualenvs/gratis/lib/python2.7/site-packages/whitenoise/base.py", line 66, in __call__ return self.application(environ, start_response) File "/Users/nhst/.virtualenvs/gratis/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__ response = self.get_response(request) File "/Users/nhst/.virtualenvs/gratis/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) File "/Users/nhst/.virtualenvs/gratis/lib/python2.7/site-packages/django/core/handlers/base.py", line 261, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/Users/nhst/.virtualenvs/gratis/lib/python2.7/site-packages/django_extensions/management/technical_response.py", line 6, in null_technical_500_response six.reraise(exc_type, … -
Creating WhiteLabel pages for an existing Django application
Am struggling on which is the best way to create white label pages for some clients an existing Django application. My current approach is that am passing an extra optional argument with a company identity and then do custom styling with the context or serve an entirely different html template. Eg below: @login_required def pay_cash(request,company=None): cart_obj = session_utils.retrieve_cart_object(request) if cart_obj is None or cart_obj.state_id != CartState.ORDER_DRAFT: logger.warn( "Pay with cash error. Cart could not be found or the state of it was not in Draft mode.") raise Http404 cart_obj.payment_type = Cart.CASH_PAYMENT_TYPE cart_obj.state_id = CartState.PAYMENT_APPROVED cart_obj.order_submitted_date = timezone.localtime(timezone.now()) cart_obj.save() if company: return redirect("order-confirmation-wlabel", company=company) else: return redirect("order-confirmation") My challenge is: 1. Is there a better way to approach the whole white labeling task 2. How do i treat pages where i can pass an extra context Eg Login and Sign up 3. Can i create decorator for these e.g @whitelabel_login_required -
Ajax Form and Django integration post errors
I am trying to store data from a form into my Database, I am using Django-Python for the backend. Here is my HTML form <form> <center> <div class="container-fluid"> <div class="row"> <div class="col-sm-5" style="background-color:white;"> <p>First name:<br></p> </div> <div class="col-sm-6" style="background-color:white;"> <p><input type="text" id="firstname"><br></p> </div> <div class="col-sm-5" style="background-color:white;"> <p>Last name:<br></p> </div> <div class="col-sm-6" style="background-color:white;"> <p><input type="text" id="lastname"><br></p> </div> <div class="col-sm-5" style="background-color:white;"> <p>Email ID:<br></p> </div> <div class="col-sm-6" style="background-color:white;"> <p><input type="text" id="email"><br></p> </div> <div class="col-sm-5" style="background-color:white;"> <p>Delivery Address:<br></p> </div> <div class="col-sm-6" style="background-color:white;"> <p><input type="text" id="address"><br></p> </div> <div class="col-sm-5" style="background-color:white;"> <p>Contact Number:<br></p> </div> <div class="col-sm-6" style="background-color:white;"> <p><input type="number" id="number"><br></p> </div> </div> </div> </center> <h1>&nbsp;</h1> <p>"Payment mode:- Cash On Delivery,</p> <p>All payment have to be done to the delivery boy by cash."</p><br> <center> <button onclick = "submitform()" class="button" style="background-color:black;color:#ffcb04;padding:5px 10px 5px 10px;border-radius: 10px">Submit</button> </center> </form> This is my javascript/Jquery/Ajax function submitform(){ firstname = $("#firstname").val() lastname = $("#lastname").val() email = $("#email").val() address = $("#address").val() number = $("#number").val() string = { 'firstname' :firstname, 'lastname' : lastname, 'email' : email, 'address' : address, 'number' : number } json_string = JSON.stringify(string); $.ajax({ type: 'POST', dataType: 'json', contentType: 'application/json; charset=utf-8', url: '/orders/store-order-details/', data: json_string, success: function(data) { window.location.href = "/confirmation/"; } }); } This is my Django views.py def store_order_details(request): received_json_data … -
'unicode' object has no attribute 'has_header'
I'm encountering and error on extracting data from db and converting it to excel, I'm using django-excel library for the task. I'm extracting user.email from my ClientContact model, and I'm creating service call that creates excel file, but I'm facing an Attribute error - 'unicode' object has no attribute 'has_header', so can someone help me understand this so I can fix it, thanks. FormView for making an excel file: from django.contrib.auth.models import User from django.http import HttpResponseBadRequest from django.http import HttpResponseForbidden from django.views.generic import FormView from django import forms import django_excel as excel from clients.models import ClientContact class UploadFileForm(forms.Form): pass class ExportClientsMailXls(FormView): template_name = 'clients/export_email/export_email.html' form_class = UploadFileForm def get(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if request.user.is_staff: return self.render_to_response( self.get_context_data(form=form, can_submit=True,)) else: return HttpResponseForbidden() def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if request.user.is_staff: if form.is_valid(): emails = ClientContact.objects.all() for email in emails: return email.user.email column_name = ['contact_email'] return excel.make_response_from_array(emails, column_name, "xls", file_name="export_client_mail") else: return HttpResponseBadRequest() else: return HttpResponseForbidden() -
select_for_update blocks forever
When I use select_for_update on a particular key, the call never returns. A regular select works: MyModel.objects.select_for_update().get(pk=pk_1) # Works But select_for_update doesn't: with transaction.atomic(): MyModel.objects.select_for_update().get(pk=pk_2) # Blocks forever I am not sure why the row would be locked. There are no other connections to the database (to be certain of this I have reset all machines with database access, but the call still blocks for this particular key). What could be the cause of this? -
add an icon to django crispy form submit button
I am struggling with the Button on a crispy form. Instead of just the default button I would like to have an icon inside The form I am currently using is like class MyForm(forms.ModelForm): helper = FormHelper() helper.layout = Layout( Div( Div(PrependedText('source_text', '<span class="fa fa-user"></span>'), css_class='col-md-6'), Div(PrependedText('destination_text','<span class="fa fa-flag-checkered"></span>'), css_class='col-md-6'), css_class='row-fluid'), Div( Div(PrependedText('departure', '<span class="fa fa-clock-o"></span>'), css_class='col-md-3'), Div('departure_delta', css_class='col-md-2'), Div(Submit('submit', "Neue Fahrt starten", css_class="btn"), css_class="col-md2"), css_class='row-fluid'), ) helper.form_show_labels = False helper.form_id = 'id_travelshare' class Meta: model = MyModel fields = ['source', 'source_text', 'destination', 'destination_text', 'departure', 'departure_delta'] widgets = { 'source': forms.HiddenInput(), 'destination': forms.HiddenInput(), 'departure' : forms.DateTimeInput(attrs={'class':'datetimepicker'}), } What I want is a button with an icon inside. I did not find an example for this. Maybe somebody has one. Kind regads Michael -
How to use Django logging AdminEmailHandler outside of the app?
I have a Django web-site. Also I have some scripts that launched by cron. Scripts and Django share some code. Also they share logging configuration. Logging configured via a big dict of string values as described here: https://docs.djangoproject.com/en/1.10/topics/logging/ In my logging config I use handler django.utils.log.AdminEmailHandler to notify admin via email about serious errors. It works inside the Django app but fails inside cron scripts: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_EXCEPTION_REPORTER_FILTER, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Is it possible to configure logging with emails inside the cron scripts? -
Django: Hold the Fancybox If There is Error after Submission
I am using Django (1.0) fancybox (0.1.4) for a contact form submission with the google reCAPTCHA checking. And I want the fancybox not to close if the reCAPTCHA validation fails in the views.py. Could anyone suggest anyway to achieve this? I attach my code as below for your reference, thanks a lot. views.py: def contact(request): if request.method == 'POST': contact_name = request.POST.get('name') contact_email = request.POST.get('email') contact_subject = request.POST.get('subject') contact_message = request.POST.get('message') recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } data = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=data) response = urllib.request.urlopen(req) result = json.loads(response.read().decode()) ''' End reCAPTCHA validation ''' if result['success']: temp_contact = db_contact(Name = contact_name, Email = contact_email, Subject = contact_subject, Message = contact_message) temp_contact.save() messages.success(request, 'Your message has been sent, thank you!') return redirect(request.META['HTTP_REFERER']) else: messages.error(request, 'Invalid reCAPTCHA. Please try again.') return render(request, 'contact.html') else: return render(request, 'contact.html') template contact.html: {% extends request.is_ajax|yesno:"fancybox/base.html,main.html" %} {% load i18n %} {% load static %} {% block content %} <form id="contact_form" class="form-horizontal" method="post" action="{% url 'contact' %}"> {% csrf_token %} <div class="form-group"> <span id="name_err" style="color:red; bold: false; font-size:1vw; padding-left:1vw; display:none">Please enter your name</span> <label class="control-label col-sm-2" for="name">Name:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="name" name="name" placeholder="Enter name here"> … -
Django - get objects having latest time in day
I have a model Scan. There are multiple scans for each Car in one day. Every scan has it's datetime accesible using Scanning object. class Car... ... class Scanning... datetime = ... class Scan... scanning = ForeignKey('Scanning'... car = ForeignKey('Car'... value = IntegerField(... valid = BooleanField(... Now I want to create a chart for a car. There will be days and values. For every day, there will be only one value (the latest valid). Since there can be multiple scans a day, I want to get the last scan in a day. Car Datetime Value 1 01.05.2017 01:00 am 1 1 01.05.2017 02:00 am 4 1 01.05.2017 04:00 am 8 1 02.05.2017 01:00 am 12 1 03.05.2017 01:00 am 7 1 03.05.2017 02:00 am 5 1 03.05.2017 03:00 am 6 1 03.05.2017 08:00 am 9 Result would be: 01.05.2017 - 8 02.05.2017 - 12 03.05.2017 - 9 Th only think I figured out is to get list of dates and for every date, get all scans - then pull the last scan. But I'm trying to find a more effective way since there can be thousands of scans. Do you know what to do? -
How to get data related to a foreign key in django rest framework?
I have to create an appointment for an event, my model is as follows - event/models.py class Event(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) event_name = models.CharField(max_length=200) event_location = models.CharField(max_length=200, default='') appointment/models.py class Appointment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) event = models.ForeignKey(Event, on_delete=models.CASCADE) appointment_date = models.DateTimeField(default=datetime.datetime.now) And appointment serializer is - appointment/serializers.py class AppointmentSerializer(serializers.ModelSerializer): class Meta: model = Appointment fields = ('id', 'event', 'appointment_date') I am able to create appointment as follows - POST appointment request params - event:6625dc74-dc36-4a22-9fac-c63e96fe6049 appointment_date:2017-06-26 18:30:00 response { "id": "08c975bc-c4d8-4e90-a4b2-bdb2cd69e9e8", "event": "6625dc74-dc36-4a22-9fac-c63e96fe6049", "appointment_date": "2017-06-26 18:30:00" } But I need event as event object, rather than event id string, like - [ "id": "08c975bc-c4d8-4e90-a4b2-bdb2cd69e9e8", "event": { "id": "6625dc74-dc36-4a22-9fac-c63e96fe6049", "event_name": "Test Event", "event_location": "TVM, IND" }, "appointment_date": "2017-06-26 18:30:00" ] -
Session for multiple users in django
I have written a code which generates set of data which gets stored in mysql tables.If a user logsin data is generated and from tables it is displayed.I am using the same table for all the users to store data..I have used sessions..The problem is when a user is logged in already and another user logsin, the data due to previous user is displayed..What is the solution so as have data for parituclar user is displayed only when that user logsin.? -
Pie chart by using django chartit
I am trying to create pie chart by using django chartit.I have a model consist of field "result". "result" has two value "passed" and "failed".So pie chart will show total number of passed and failed .would any of you know how to show this in django? model: class Results(models.Model): tsname=models.ForeignKey(Tsname) buildname = models.CharField(max_length=200) result = models.CharField(max_length=200) date = models.DateField(null=True) Urls: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<tsname_id>[0-9]+)/$', views.detail, name='detail'), url(r'^chart-test/$',views.chart, name='chart'), ] View: def chart(request): resultdata = DataPool( series= [{'options': { 'source': Results.objects.all()}, 'terms': [ 'buildname', 'result']} ]) def resultname(name): names={1:'passed', 2:'failed'} return names[name] cht = Chart( datasource = resultdata, series_options = [{'options':{ 'type': 'pie','stacking': False, }, 'terms':{ 'buildname': [ 'result'] }}], chart_options = {'title': { 'text': 'Result of test cases'}, }, x_sortf_mapf_mts = (None, resultname, False) ) return render_to_response('mbr/chart.html',{'resultchart': cht}) chart.html: {% extends "base.html" %} {% block content %} <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script src="http://code.highcharts.com/highcharts.js" type="text/javascript"></script> {% load chartit %} {{ resultchart|load_charts:"container" }} </head> <body> <div id='container'>{{ resultchart|load_charts:"container" }} </div> </body> {% endblock%} -
Celery Task class with DRF serializer
I tried using Celery Task & Django rest framework serializer in same class with multiple inheritance. from celery import Task class ReceiveSerializer(Task, serializers.Serializer): def run(self, source, *args, **kwargs): self.save() def save(self, **kwargs): # call long running save method I got error, File "<>\serializers.py", line 217, in <module> class ReceiveSerializer(Task, serializers.Serializer): File "<>\workspace\www\lib\site-packages\celery-3.1.20-py2.7.egg\celery\app\task.py", line 199, in __new_ _ tasks.register(new(cls, name, bases, attrs)) TypeError: Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases The save method has to create long list of objects in db (some times more than 5 minutes). I don't want user to wait for long time. Is there any way to do this. -
Retrieving EmbeddedDocument using python and django
I have below set of code : class first(EmbeddedDocument): var1 = StringField() var2 = ListField() class second(EmbeddedDocument): var1 = ListField(EmbeddedDocumentField(first)) var2 = StringField() class main(Document): var1 = ListField(EmbeddedDocumentField(second)) other fields I am able to store the data perfectly. For reading the data, I am creating the object of main and try to read the fields. I am able to read the all other fields except embedded data. Please help. Thanks in advance! -
Django+Bokeh+autoload_server : get one div by figure
Using Bokeh 0.12.4 and django 1.10.6, how can I obtain a script for individual figure by using autoload_server. In myapp/main.py: from bokeh.plotting import Figure fig1= Figure(plot_width=500, plot_height=300, name='fig1') fig2 = Figure(plot_width=500, plot_height=300, name='fig2') curdoc().add_root(fig1) curdoc().add_root(fig2) In mysite/views.py, I would like to do something like that: from django.shortcuts import render from bokeh.embed import autoload_server def index(request): script1 = autoload_server(model='fig1', url="http://localhost:5006/myapp") script2 = autoload_server(model='fig2', url="http://localhost:5006/myapp") return render(request, 'index.html', context={'script1': script1, 'script2': script2}) And then put the scripts where I want in the html template mysite/templates/index.html: <div> {{script1 | safe }} </div> <div> {{script2 | safe }} </div> -
use __gte for string date django
Date is in string format in database class A(models.Model): date = models.CharField(max_length=50, blank=True, null=True) Yah i know it should be date type. but now we have many records and we will soon change it to date type. For current status i want get the objects greater than particular date. So how can i use date__gte example objs = A.objects.filter(date__gte=datetime.now()) Is there any way to achieve this without converting date to datetime field. -
Custom Django Wagtailmenus Flatmenu Template
I am using https://github.com/rkhleics/wagtailmenus for my Django Wagtail menus, but can't seem to figure out how to use a custom template for my flat_menu. I followed the guides but I think I may be doing something wrong. My flat_menu template is in a directory menus/top_sub_menu.html, where top_sub_menu is the handle of the menu I created. top_sub_menu.html {% load menu_tags %} {% if menu_items %} <ul class="c-links c-theme-ul"> {% for item in menu_items %} <li> <a href="{{ item.href }}">{{ item.text }}</a> {% if item.has_children_in_menu %}{% sub_menu item %}{% endif %} </li> {% endfor %} </ul> {% endif %} header.html {% load menu_tags %} ... {% flat_menu 'top_sub_menu' %} ... I have a custom main_menu.html and a sub_menu.html in the same directory and they work, so I know my menu directory is in correct location. Thank you. -
Validationerror in clean methods in Django forms not working
I am trying to create a form that will make the user select at least one option from the radioselect. However my clean form methods are not working. I hope someone can spot where the issue is with my forms.validationerror method. I tried to my form below credit_choices = ( ('100', '100 credits - $10'), ('200', '200 credits - $18 - 11% Savings'), ('500', '500 credits - $40 - 25% Savings'), ('1000', '1000 credits - $70 - 43% Savings'), ('2000', '2000 credits - $120 - 67% Savings'), ) class CreditForm(forms.Form): credit = forms.ChoiceField( label='Select Amount of Credits to Purchase', choices=credit_choices, widget=forms.RadioSelect(), required=True ) I also tried to clean the form suing the different variations of two methods. The clean_field() and the clean(). I was able to print "None" or the parameter that was chosen but the will skip the step of going into forms.Validationerror and go into Valueerror on the page. def clean_credit(self): credit = self.cleaned_data.get("credit") print credit if credit == None: print "test" raise forms.ValidationError("Please choose one") return credit def clean(self): cleaned_data = super(CreditForm, self).clean() credit = self.cleaned_data.get("credit") print credit if not credit: print "test" raise forms.ValidationError("Please choose one") return cleaned_data My view is in the attached below. class … -
Django - Apache : How to change static repertory for upload files
I installed Django on a VPS and Apache2, but when I want to upload a file (Avatar with userena) I have this error Permissions refused: 'var/www/static' but my css files and others have Loaded (file in the static directory of my project), And the directory of my django project is in /home/user/... and not in /var/www, I tried a "DocumentRoot" change in `etc/apache2/site-available/000-Default.conf..'But it does not work My conf in 000-default.conf : ``` ServerName www.site_example.com ServerAdmin webmaster@site_example DocumentRoot home/ubuntu/my_site/site_example/ Alias /static /home/ubuntu/my_site/site_example/static <Directory /home/ubuntu/my_site/site_example/static > Require all granted </Directory> <Directory "/home/ubuntu/my_site/site_example"> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess site_example python-path=/home/ubuntu/my_site/site_example python-home=/home/ubuntu/web_sites/my_site__venv WSGIProcessGroup site_example WSGIScriptAlias / /home/ubuntu/my_site/site_example/wsgi.py ```