Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
what is 'mpoly' : 'MULTIPOLYGON' in Geodjango , what should be its default value if its blank
I am working on example from [https://docs.djangoproject.com/en/1.11/ref/contribt/gis/tutorial/][1] using mysql as database, followed most of the steps given and while trying to load data using load.run() as in the doc, seems like # GeoDjango-specific: a geometry field (MultiPolygonField) mpoly = models.MultiPolygonField() is blank, and needs a default value, what should be the default value of this field. Is it ok to keep it blank. The data needed is : world_mapping = { 'fips' : 'FIPS', 'iso2' : 'ISO2', 'iso3' : 'ISO3', 'un' : 'UN', 'name' : 'NAME', 'area' : 'AREA', 'pop2005' : 'POP2005', 'region' : 'REGION', 'subregion' : 'SUBREGION', 'lon' : 'LON', 'lat' : 'LAT', 'mpoly' : 'MULTIPOLYGON', } while command line shows this data, which does not have 'mpoly' field {'pop2005': 83039, 'region': 19, 'fips': 'AC', 'lat': 17.078, 'subregion': 29, 'name': 'Antigua and Barbuda', 'un': 28, 'iso3': 'ATG', 'iso2': 'AG', 'area': 44, 'lon': -61.783} -
LEFT OUTER JOIN in Django
I have two models class Topic(models.Model): name = models.CharField(max_length=200,verbose_name="Topic name") description = models.TextField(default="") class Comment(models.Model): message = models.TextField(default="") user = models.ForeignKey(to=User,related_name="user_comments",on_delete=models.CASCADE) topic = models.ForeignKey(to=Topic, related_name="comments",on_delete=models.CASCADE) How can i do a LEFT outer join of Topic Model on Comments for a particular "user" made "comment". The equivalent Sqlite query is like SELECT * FROM topic_topic a LEFT OUTER JOIN topic_comment b ON b.topic_id=a.id AND b.user_id=1 Is there a good way of doing this in django queryset? Please let me know -
django: Better implementation of LEFT JOIN
I have two models, class Post(models.Model): id = models.IntegerField(primary_key=True) post_title = models.CharField() post_type = models.CharField() class Comments(models.Model): id = models.IntegerField(primary_key=True) post = models.ForeignKey(Post, related_name="post_comments") comment = models.CharField() user_id = models.IntegerField() I want to get "all" posts with post_type "blog" along with comments of a specific user. If am doing it with raw query, the query will be like this, SELECT p.id as post_id, p.post_title, pc.comment FROM Post p LEFT JOIN Comments pc ON (p.id=pc.post AND pc.user_id=20) WHERE p.post_type='blog' The above query will return all posts with post_type as "blog" along with comments by user_id 20. How can I implement this in django? I tried the bellow method, But it didnt work. queryset = Post.objects.filter(post_type='blog', post_comments__user_id=20).all() I googled a lot but I couldnt find a good solution for this. -
Django: python manage.py migrate does nothing at all
I just started learning django, and as i try to apply my migrations the first problem occurs. I start the server up, type python manage.py migrate and nothing happens. No error, no crash, just no response. Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. May 01, 2017 - 11:36:27 Django version 1.11, using settings 'website.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. python manage.py migrate And that's the end of my terminal feed. I thought maybe it just looks like nothing happens, but no. The changes weren't applied and I can't proceed any further. Any ideas on what's going on? -
Smallest unused id from mysql table with django
suppose i have a table A(id, x, y). I've inserted where id = 1 to 35 but 15, 18 etc. is there a way to find the smallest unused id in django. what should i do to insert with smallest available id available whenever i add an item. there are some similar questions i found on stackoverflow that explains how to do it in mysql(links below). but as i am very new to django i am not getting how to do that in django. mysql find smallest + unique id available -
DRF and HStoreField?
I have a model with HStoreField: When I try view in browser I get: AttributeError at /test/ 'str' object has no attribute 'items' I set the breakpoint on to_representaion method in DictField and I see: def to_representation(self, value): self: CharMappingField() value: ' "key"=>"value" ' """ List of object instances -> List of dicts of primitive datatypes. """ return { six.text_type(key): self.child.to_representation(val) if val is not None else None for key, val in value.items() } value is string, but must be dict. It is a model and serializer: class Test(models.Model): field = HStoreField() class TestSerializer(serializers.ModelSerializer): class Meta: model = Test fields = '__all__' Same I can not add a new value: ProgrammingError at /test/ can't adapt type 'dict' Django version (1.11), Rest Framefork (3.6.2) Thanks for any help! -
How to connect a microsoft azure SQL server to django webapp
I am working on a Django webapp, and for this app I would like to have an online database. It just so happens my faculty grants access to using some Microsoft Azure services, including SQL databases. Now, I would like to connect an Azure SQL database to my Django project, however I cannot get this to work. I can connect to the database through PyCharm's data source view, however using the same parameters in settings.py yields this error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03846270> Traceback (most recent call last): File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File … -
Convert nested dict/json to a django ORM model, without hard coding the data structure
I want to import data from json files into my django db. The json contains nested objects. Current steps are: Set up my django models to match the json schema (done - see below) Import json file into python dict using mydict = json.loads(file.read()) (done) Convert dict to django models (done - but solution is not pretty) Is there a way I can convert my nested dict into django models without hard-coding the data structure? Bonus points for automatically generating the django models (i.e. the models.py file). Thanks in advance! How I'm currently doing it Step 3 is easy if the dict does not contain any nested dicts - just construct a new object from the dict i.e. MyModel.objects.create(**mydict) or use django fixtures. However, because my json/dict contains nested objects, I'm currently doing step 3 like this: # read the json file into a python dict d = json.loads(myfile.read()) # construct top-level object using the top-level dict # (excluding nested lists of dicts called 'judges' and 'contestants') c = Contest.objects.create(**{k:v for k,v in d.items() if k not in ('judges', 'contestants')}) # construct nested objects using the nested dicts for judge in d['judges']: c.judge_set.create(**judge) for contestant in d['contestants']: ct = c.contestant_set.create(**{k:v … -
Error adding new models to database Django
models.py class Genre(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name Genres.py from MyVideoGames.models import Genre from ClientIGDB import ClientIGDB genres = ClientIGDB.api_call("genres", ["name"], 50) for genre in genres: g = Genre.objects.create(name=genre["name"]) g.save() When I'm trying to add some models to sqlite db i'm not able to do this import: from myproj.models import Genre. I don't know why... When I do it this error is shown: % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. If someone can help me I'll be really gratefull -
How to Additional attribute to object
Im new to Django and Python which I'm using to create a Hotel Booking website. Im trying to fetch all the rooms associated with a hotel With the returned object Im trying to add an extra attribute onto each room returned. This attribute will equal a variable . Example: rooms = Room.object.filter(hotel=thehotel) // for each room in rooms Roomsavailable = Room.totalrooms Roomsleft = RoomsAvailable - RoomsBooked //attach roomsleft onto each room object room.spaceleft = Roomsleft Any help would be appreciated , hope i've explained it ok. -
How to serve an image with a different random name each time with Django?
I'm implementing some sort of image captcha for a client, and my client requested the images be served with a different URL on each challenge attempt. My web server is Django and I currently serve the images using nginx locally but I plan to host the images on S3. What's the best approach to do this? I could: Use Django to declare a python view that would download the image from where it is originally hosted and serve it under the random name;(the name saved under the challenge attempt instance). Use Django to call on the file system or to call Amazon API to copy the file to a random name, when the challenge is initialised, and then delete that file later when triggered by the solving of a challenge relating to that image. The reason I'm asking is because Django isn't efficient in serving static data. Any other ideas? -
Django app to have this sequence: One add -> Video call with screen sharing -> Rate the call and donation. Any tips on how to implement this pipeline?
In your answers I would love if you included a reasoning behind your tip. Any programming language is welcome, though I would prefer Java, Python, C, and/or C++. The add should be something like the ones in youtube videos, in which you can't skip it as it is short (so money is guaranteed). Maybe use AdSense? Thank you -
Django runserver gives me syntax error
python manage.py runserver Performing system checks... Unhandled exception in thread started by Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib__init__.py", line 37, in import_module import(name) File "C:\Users\Kaidi\Desktop\CM2\CM\CM\urls.py", line 18, in from mysite import views File "C:\Users\Kaidi\Desktop\CM2\CM\mysite\views.py", line 2, in from rest_framework import viewsets, permissions, status File "C:\Python27\lib\site-packages\rest_framework\viewsets.py", line 26, in from rest_framework import generics, mixins, views File "C:\Python27\lib\site-packages\rest_framework\generics.py", line 10, in from rest_framework import mixins, views File "C:\Python27\lib\site-packages\rest_framework\views.py", line 98, in class APIView(View): File "C:\Python27\lib\site-packages\rest_framework\views.py", line 103, in APIView authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES File "C:\Python27\lib\site-packages\rest_framework\settings.py", line 220, in getattr val = perform_import(val, attr) File "C:\Python27\lib\site-packages\rest_framework\settings.py", line … -
How to use MultipleChoiceField in django-widget-tweaks?
I have form with MultipleChoiceField field which has dynamic list for choices. With the help of this form users can select data and add them to database. Sometimes dynamic list can be empty []. So I want to show message in template when its empty but next code didnt show me message. I use django-widget_tweaks application in my template. Where is my mistake? forms.py: class RequirementForm(forms.ModelForm): symbol = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple) class Meta: model = Requirement fields = ('symbol',) requirement_add.html: {% load widget_tweaks %} <form method="post" action="{% url 'project:requirement_add' project_code=project.code %}"> {% for field in form %} {% render_field field class="form-control" %} {% empty %} <p>Form is empty!</p> {% endfor %} </form> -
ALLOWED_HOSTS error in Django app on Digital Ocean. Setting the variable does not resolve the error
I followed this guide to set up a Django app on DO: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-16-04 However, I'm unable to get past the common ALLOWED_HOSTS error, where everyone typically forgets to put anything in the list and its a simple fix. Even with the correct values entered, or with the catch-all "*", the error persists. I've never had this happen before, so I'll put my configuration files here to get some more eyes on it. Any ideas as to what could be causing this? contents of /etc/uwsgi/sites/myapp.ini: [uwsgi] project = myapp uid = myuser base = /home/%(uid) chdir = %(base)/%(project) home = %(base)/%(project)/venv module = %(project).wsgi:application master = true processes = 5 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):www-data chmod-socket = 660 vacuum = true contents of /etc/systemd/system/uwsgi.service: [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown myuser:www-data /run/uwsgi' ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target contents of /etc/nginx/sites-available/myapp: server { listen 80; server_name mydomain.com www.mydomain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myuser/myapp_static; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/myapp.sock; } } -
How Connect angular 2 to Django?
I have a problem to connecting angular 2 to django. I want to send some data from http post request and in django use this data that sent from http request(Save to model,show,etc). I tried some code but that doesn't worked. Can anyone help me to fix my problem??? Thanks a lot. -
I couldn't store the values in database from the custom form in HTML page. Using Django
This is my views.py file. from django.shortcuts import render, redirect from .forms import RegistrationForm def index(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() else: form = RegistrationForm() args = {'form': form} return render(request, 'Login/index.html', args) This is my models.py file from django.db import models class Customer(models.Model): fname = models.CharField(max_length=25) company = models.CharField(max_length=15) email = models.CharField(max_length=15) password1 = models.CharField(max_length=15) password2 = models.CharField(max_length=15) def __str__(self): return self.company + ' - ' + self.fname Following is my forms.py file from django import forms from django.forms import ModelForm from .models import Customer class RegistrationForm(forms.ModelForm): email = forms.EmailField(required=True) class Meta: model = Customer fields = ( 'fname', 'company', 'email', ) def save(self, commit=True): user= super(RegistrationForm, self).save(commit=False) user.UserName= self.cleaned_data.get['name'] user.CName = self.cleaned_data.get['cname'] user.Email = self.cleaned_data.get['email'] if commit: user.save() return user And HTML file is: <!DOCTYPE html> <html> <head> <link rel="shortcut icon" href="favicon.ico"/> <title>Customer Desk</title> {% load static %} <link href="{% static 'css/Styles.css' %}" rel="stylesheet" type="text/css" /> </head> <body class="login"> <!-- header starts here --> <div id="desk-Bar"> <div id="desk-Frame"> <div id="logo"> <a href="http://127.0.0.1:8000/Home/">Virtual Agent </a></div> <div id="header-main-right"> <div id="header-main-right-nav"> <form method="post" action="" id="login_form" name="login_form"> <table border="0" style="border:none"> <tr> <td ><input type="text" tabindex="1" id="mail" placeholder="Email or Phone" name="email" class="inputtext radius1" value=""> </td> <td ><input type="password" … -
Django Rest framework, POST FOREIGN KEY
I'm trying to post a nested object, and im getting the following error: Column person_id cannot be null Here's my serializer,model and my view. Model.py class Person(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) curp = models.CharField(max_length=50) rfc = models.CharField(max_length=12) gender = models.CharField(max_length=20) class Employee(models.Model): id = models.IntegerField(primary_key=True) joining_date = models.DateField() salary = models.DecimalField(18, decimal_places=2, max_digits=50) status = models.IntegerField() person = models.ForeignKey(Person, related_name='persons', on_delete=models.CASCADE) user = models.ForeignKey(User) branch = models.ForeignKey(Branch) Serializers.py class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ('__all__') class EmployeeSerializer(serializers.ModelSerializer): persona = PersonSerializer(read_only=False) usuario = UserSerializer(read_only=False) sucursal = Serializer(read_only=False) class Meta: model = Employee depth = 1 fields = ('__all__') def create(self, validated_data): person_data = validated_data.pop('person') user_data = validated_data.pop('user') branch_data = validated_data.pop('branch') employee = Empployee.objects.create(**validated_data) for person_data in person_data: Person.objects.create(employee=employee, **person_data) #### Code for user and branch #### return empleado Views.py class ListCreateEmployee(generics.ListCreateAPIView): queryset = Employee.objects.all() serializer_class = EmployeeSerializer I've added the method create as i've read it in the django rest website but i didnt understand how to call that method. -
Django - Generic detail_view doesn't accept an object_list
I have the following in urls.py: url(r'frameworkslist/(?P<pk>\d+)$', DetailView.as_view(queryset=Category.objects.all().order_by("id"), template_name='home/subcategory.html')) And in my html template: {% extends "Layout.html" %} {% block content %} {{ subcategory.Name }} {% for item in object_list %} <h5> <a href="/search/{{ item.id }}">{{ item.Name }}</a> </h5> {% endfor %} <a href = "/frameworkslist/">Back to framework list</a> {% endblock %} I was wondering why object_list was empty but when I changed my urls to the following, it worked. (returned the ListView template instead of DetailView): url(r'frameworkslist/(?P<pk>\d+)$', ListView.as_view(queryset=Subcategory.objects.all().order_by("id"), template_name='home/subcategory.html')) Also to note, it seems like passing the variable "model=Subcategory" to the DetailView would return the first record (or what should be a single model) of the Subcategory table and pass that to the Template. So my question is two-part, the second being: How do you a collection of objects to DetailView Template? -
How to use django-notifications to inform a user when somebody sends a new request to them
I have been developing in Django for some time now, and have developed a neat website having functionality such as sending requests to a user and accepting of the request. However, there is still one thing that is missing and i.e. creating a notification for users. What I want to do is to inform users in their profiles, whenever somebody sends a new request to them, or if they somebody accept the request. -
(django) (docker) postgres wont run and wont start
I run docker-compose up i get: $ docker-compose up Starting asynchttpproxy_db_1 Starting asynchttpproxy_web_1 Attaching to asynchttpproxy_db_1, asynchttpproxy_web_1 db_1 | LOG: database system was shut down at 2017-05-01 05:11:54 UTC db_1 | LOG: MultiXact member wraparound protections are now enabled db_1 | LOG: database system is ready to accept connections web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x7fae3f078e18> web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/site- packages/django/db/backends/base/base.py", line 130, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.6/site- packages/django/db/backends/base/base.py", line 119, in connect web_1 | self.connection = self.get_new_connection(conn_params) web_1 | File "/usr/local/lib/python3.6/site- packages/django/db/backends/postgresql_psycopg2/base.py", line 176, in get_new_connection web_1 | connection = Database.connect(**conn_params) web_1 | File "/usr/local/lib/python3.6/site- packages/psycopg2/__init__.py", line 164, in connect web_1 | conn = _connect(dsn, connection_factory=connection_factory, async=async) web_1 | psycopg2.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "localhost" (127.0.0.1) and accepting web_1 | TCP/IP connections on port 5432? web_1 | could not connect to server: Cannot assign requested address web_1 | Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5432? … -
How to run files my files Django/python in Google App Engine Standard Environment ( manage.py, ... )
I am running a Django python app locally perfectly but I am lost when I deploy it in Google App Engine. Indeed, locally I am used to run python manage.py makemigrations python manage.py migrate and on Google App Engine I can't find these files in the Google Shell. I use BitBucket as a repo and gcloud app deploy to deploy the code from the repo BitBucket. However, when I go into Cloud Shell, I can't find my files to run the migrate command. I could checkout them locally... and I did, but they are not the "same" files... In Cloud Storage, I can see 2 items, but I can locate them in the Cloud Shell. hiking-164708.appspot.com staging.hiking-164708.appspot.com and I want to run the migrate cmd, because I have an issue with my /admin, other TABLEs work... So my question: Where is my manage.py file ? here is my app.yaml runtime: python27 api_version: 1 threadsafe: true handlers: - url: /.* script: main.application libraries: - name: django version: "1.4" - name: MySQLdb version: "latest" env_variables: DJANGO_SETTINGS_MODULE: 'ghiking.settings' -
Django Logging not outputting to log file on nginx server
My Django Logger works fine on my local machine but does not work when I deploy it to the server. Local: OS X 10.9.5, Python 2.7, Django 1.10.5 AWS Server: Ubuntu, Nginx, Gunicorn, Django On my local setup I run python manage.py runserver, this creates the debug.log file in my root directory. I access the site through localhost:8000 when I boot up the local server via virtual environment and I get these logs on my debug.log. "GET / HTTP/1.1" 200 2908 "GET /projects HTTP/1.1" 200 3461 Inside app views index On my production server I run python manage.py runserver, this creates the debug.log file. I restart Nginx server by sudo service nginx restart, and I access my webpage and click on the same links as when I was running the local server. When I vim debug.log into the debug.log file, I can not see any of my debug messages after I visit the website and click on the same links in the webpage. Why is there no logging data being recorded into debug.log on my production environment? What am I missing? views.py import logging logger = logging.getLogger(__name__) def index(request): logger.debug('Inside app views index') return render(request, "first_app/index.html") local_settings.py (It shouldn't matter, … -
Django date-filter - Need month filter
I'm using django_filters to get the filter component. Objective is to have month and year filter component. I'm able to achieve to get complete Date-Month-Year picker. How will I get just Month-Year filter. import django_filters as filters. class xyz(filters.FilterSet): schedule_date = filters.DateFromToRangeFilter(name='schedule_month', widget=filters.widgets.RangeWidget(attrs={'class': 'datepicker'})) class Meta(object): form = forms.Form I tried to use input_formats = ['%m-%Y'] - schedule_date = filters.DateFromToRangeFilter(name='schedule_month',input_formats = ['%m-%Y'], widget=filters.widgets.RangeWidget(attrs={'class': 'datepicker'})) But got an error TypeError: init() got an unexpected keyword argument 'input_format' Any way to get this done? Any other widget say monthpicker rather than datepicker ? -
one url for views with id and not with id
Is there a way to use only one url for the views to display the content with id(token) and without id(token). For example there is a view which displays the list of profile of user if token is not provided otherwise show a specific user with the token that is passed. Here is a view def get(self, request, token=None, format=None): """ Returns a list of profile of user or single user if token is provided """ reply={} try: profile_instance = Profile.objects.filter(user=self.request.user) if token: profile = profile_instance.get(token=token) reply['data'] = self.serializer_class(profile).data else: reply['data'] = self.serializer_class(profile_instance, many=True).data except: reply['data']=[] return Response(reply, status.HTTP_200_OK) The url wil be something like this url( r'^users/$', views.UserList.as_view(), name="user_list" ), url( r'^users/(?P<token>[0-9a-z]+)$', views.UserList.as_view(), name="user_profile" ), Is there a way to have only one url?