Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i take nested forms in django?
Below is forms.py code and i want to take one more nested form class Pay_bills(forms.ModelForm): class Meta: model = Recharge_request fields = ['mobile_no','amount'] -
How to order the values in a MPTT model?
I have a MPTT django model and I want to short all the values alphabetically independently of the level_indicator. More specifically I have set the level_indicator as: level_indicator=u'' I have tried to add the ordering parameter in my model as: class MPTTMeta: order_insertion_by = ['name'] but this doesn't work. I also tried to add the order parameter in the queryset as: queryset=Region.objects.all(), But this also doesn't give the desired result. Any suggestions? -
nginx, headers are missing when response is 403
I am using nginx + uwsgi. When the response is 200~299, the all the headers set are present in response, but in response like 400,401, 403 the headers are missing server { listen 80 default_server; server_tokens off; location / { include uwsgi_params; uwsgi_pass django; } add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;"; add_header X-Frame-Options SAMEORIGIN; add_header X-Content-Type-Options nosniff; add_header X-XSS-Protection "1; mode=block"; -
Django REST "Cannot resolve keyword 'user' into field" error
I'm trying to add a password reset url to the object details. I included the user in userinformations model as a foreign key. The url link appears in the detail but when I click it I get the aforementioned error. serializers.py class UserPasswordResetSerializer(ModelSerializer): password = serializers.CharField(style={'input_type': 'password'}, label="Enter New Password") password2 = serializers.CharField(allow_blank=False, label="Confirm New Password") user = UserSerializer() class Meta: model = User fields = ['user', 'password', 'password2'] extra_kwargs = { 'password': { 'write_only': True, }, 'password2': { 'write_only': True, }, } def validate(self, data): """ Checks to be sure that the received password and confirm_password fields are exactly the same """ if data['password'] != data.pop('password2'): raise serializers.ValidationError("Passwords do not match") return data views.py class UserPasswordReset(RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = UserPasswordResetSerializer lookup_field = 'user' urls.py urlpatterns = [ url(r'^(?P<user>.+)/password/$', views.UserPasswordReset.as_view(), name='password'), ] -
Show message with Ajax in modal window
I have little problem in my Django project. My project has modal window where users create new object. There is only one field (name) in that modal window. Also I use AJAX. I am tring to check if the same object is already exist and show message in that modal. You can see code which I tried to use but unfortunatly I dont see any messages. How can I make message in Ajax? views.py: def function_add(request, project_code): data = dict() project = get_object_or_404(Project, pk=project_code) if request.method == 'POST': form = FunctionAddForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] if Function.objects.filter(name=name, project=project_code).exists(): messages.warning(request, 'Already exist.') else: function = form.save(commit=False) function.project = project function.save() data['form_is_valid'] = True functions = Function.objects.filter(project=project_code) data['html_function'] = render_to_string('project/function_list.html', {'functions': functions}) else: data['form_is_valid'] = False else: form = FunctionAddForm() context = {'project': project, 'form': form} data['html_function_add_form'] = render_to_string('project/function_add.html', context, request=request) return JsonResponse(data) function_add.html: {% if messages %} <ul class="messages"> {% for message in messages %} <li class="{{ message.tags }}">{{ message }}</li> {% endfor %} </ul> {% endif %} -
I have downloaded a Django app for login from, but it doesnt have a manage.py file but a setup.py file. How to make it work on Virtualenv?
I am using Python Version - 2.7 and Django Version - 1.10.5, I have read the documents but as I am totally new to Django, the documentation steps are not very clear. -
Purposes of JSON files
I am working since two weeks with a programmer's team. Our project is with Python and Django. I can't understand why we use JSON files. In fact, they asked me to use dumpdata to transfert data from a template in django to a .json file. Could anyone have time to explain to me why they use such files. -
Django retrieve a list of items from form
I have a quiz view that displays a list of questions and textarea for students to key in their answers. As I'm new to Django, I wonder what is the correct way to get the list of students answers from the post method? Here is my current code: forms.py class TakeTestForm(forms.Form): student_answer = forms.CharField(widget=forms.Textarea, label='') views.py class TakeTestFormView(FormView): def post(self, request, *args, **kwargs): submit_answer_form = self.form_class(request.POST) if submit_answer_form.is_valid(): answer_list = request.POST['student_answer'] ?? # TODO: Retrieve list of answers from the form index.html {% for question in qst_data %} <div id="action-container"> {{ take_test_form.as_p }} </div> % endfor %} -
Error searching in Django admin
Here is the relevant part of my code: model.py class Blogger(models.Model): identity = models.ForeignKey(User, models.SET_NULL, null=True) def __str__(self): return self.identity.username admin.py @admin.register(Blogger) class BloggerAdmin(admin.ModelAdmin): list_display = ('__str__', 'identity') search_fields = ['__str__'] I went to http://127.0.0.1:8000/admin/blog/blogger/, typed user in the search field, hit Search, and got an FieldError: FieldError at /admin/blog/blogger/ Cannot resolve keyword '' into field. Choices are: bio, blog, comment, id, identity, identity_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/blog/blogger/?q=user Django Version: 1.10.6 Exception Type: FieldError Exception Value: Cannot resolve keyword '' into field. Choices are: bio, blog, comment, id, identity, identity_id Exception Location: /Users/sunqingyao/Envs/django_test/lib/python3.6/site-packages/django/db/models/sql/query.py in names_to_path, line 1327 Python Executable: /Users/sunqingyao/Envs/django_test/bin/python Python Version: 3.6.0 Python Path: ['/Users/sunqingyao/PycharmProjects/diyblog', '/Users/sunqingyao/PycharmProjects/diyblog', '/Users/sunqingyao/Envs/django_test/lib/python36.zip', '/Users/sunqingyao/Envs/django_test/lib/python3.6', '/Users/sunqingyao/Envs/django_test/lib/python3.6/lib-dynload', '/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Users/sunqingyao/Envs/django_test/lib/python3.6/site-packages'] Server time: Tue, 28 Mar 2017 13:01:58 +0800 When I change search_fields = ['__str__'] to search_fields = ['identity'] I got an TypeError instead: TypeError at /admin/blog/blogger/ Related Field got invalid lookup: icontains Request Method: GET Request URL: http://127.0.0.1:8000/admin/blog/blogger/?q=user Django Version: 1.10.6 Exception Type: TypeError Exception Value: Related Field got invalid lookup: icontains Exception Location: /Users/sunqingyao/Envs/django_test/lib/python3.6/site-packages/django/db/models/fields/related.py in get_lookup, line 694 Python Executable: /Users/sunqingyao/Envs/django_test/bin/python Python Version: 3.6.0 Python Path: ['/Users/sunqingyao/PycharmProjects/diyblog', '/Users/sunqingyao/PycharmProjects/diyblog', '/Users/sunqingyao/Envs/django_test/lib/python36.zip', '/Users/sunqingyao/Envs/django_test/lib/python3.6', '/Users/sunqingyao/Envs/django_test/lib/python3.6/lib-dynload', '/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Users/sunqingyao/Envs/django_test/lib/python3.6/site-packages'] Server time: Tue, 28 Mar 2017 13:12:09 +0800 What value should I … -
Sorl-thumbnail - ValueError: unknown color specifier
I am using sorl-thumbnail 12.3 in a django model like below. from sorl.thumbnail import get_thumbnail class InsuranceCompany(Model): logo = ImageField(upload_to='company_logo/%Y/%m/%d', null=True) @property def logo_cropped(self): if self.logo: return get_thumbnail(self.logo, "250x250", crop="center").url While it works most of the times, sometimes it gives the following error for some images (mostly for png images, or I felt so): -> 2031 color = ImageColor.getcolor(color, mode) 2032 2033 return Image()._new(core.fill(mode, size, color)) /home/ubuntu/.virtualenvs/.../python2.7/site-packages/PIL/ImageColor.pyc in getcolor(color, mode) 126 """ 127 # same as getrgb, but converts the result to the given mode --> 128 color, alpha = getrgb(color), 255 129 if len(color) == 4: 130 color, alpha = color[0:3], color[3] /home/ubuntu/.../python2.7/site-packages/PIL/ImageColor.pyc in getrgb(color) 111 int(m.group(4)) 112 ) --> 113 raise ValueError("unknown color specifier: %r" % color) 114 115 ValueError: unknown color specifier: '\x004\x88\x86u\x84\xa1\xac\x8a\t\xcfr6\xf9c~t\x10\xd7p\x8ch-mf\x9d\xaa\xb2\xb7\xb0\xa2\x8f`;\r\x1ffl\x93\xa7\xaf\xb3\x8a;h\x02\x19\'8to\x9c\xae`&\x83\x98d\x12\x05\x10\x9b\xca\xf4\xfd\xce#\xb1\xe8\xd12\xbb\x819\xbf\xc5\xd1\xe2\xf1\x91\xc1\xee\xdc~w[\x86ld\xe0[^\xd2\x0c\xba\xb9h\xe8n\xf4t[=\xc0?k\xb0:\xfa{!\xeb\x92|4\xf7.\x9cgr\x17cuxko\xf5\x0c\xd8\x10\x1b\x07\x1d\xe3\xf1\xb5\xec\xb7*\xfd\xcb\xf0s\xd8\xb6\xc1\xe6\xdc\x1c\xe8\xad\xec\x1f\xe7\xe5\xfe\xeb\xe2).2\x05\x96\x17\xf9\x1c\x1a\xbdo\x14\xc5\xc6|\xc9t\xb4&\xd9\xf9"\xe4\xdc%\xdexh\n\xdfd\xdf\xd0\xc4\x1b"\xcb\x18\xdf\xce\x16t\n\xcd*ju\xa9dk\xab\x0e\xd2p\xa0\xd2~h\x9a\xb3\xb7r\xca@\xab\xa5\xba\xb8\xbb{\x15x|' Please help. -
Cannot login to admin with custom backend in Django 1.11.rc1
Using Django 1.10 I have no problem using my custom backend to login (not a custom user just the auth) but in 1.11rc1 I get the following exception: Request Method: POST Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 1.11rc1 Exception Type: FieldError Exception Value: Cannot resolve keyword 'request' into field. Choices are: clientcontact, crudevent, date_joined, email, <...just more fields> The backend: def authenticate(self, **kwargs): if kwargs: username = kwargs.pop("username", None) if username: username_or_email = Q(username=username) | Q(email=username) password = kwargs.pop("password", None) try: user = User.objects.get(username_or_email, **kwargs) except User.DoesNotExist: pass else: if user.check_password(password): return user else: ... In settings.py: AUTHENTICATION_BACKENDS = ('base_app.auth_backend.JbcBackend', 'guardian.backends.ObjectPermissionBackend',) I haven't been able to find anything, if someone could point me in the right direction that would be great. Here is the full Traceback: Traceback: File "/home/mat/.virtualenvs/jbcarcenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/mat/.virtualenvs/jbcarcenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/mat/.virtualenvs/jbcarcenv/lib/python3.6/site-packages/channels/handler.py" in process_exception_by_middleware 237. return super(AsgiHandler, self).process_exception_by_middleware(exception, request) File "/home/mat/.virtualenvs/jbcarcenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/mat/.virtualenvs/jbcarcenv/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/home/mat/.virtualenvs/jbcarcenv/lib/python3.6/site-packages/django/contrib/admin/sites.py" in login 393. return LoginView.as_view(**defaults)(request) File "/home/mat/.virtualenvs/jbcarcenv/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/mat/.virtualenvs/jbcarcenv/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/home/mat/.virtualenvs/jbcarcenv/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper … -
bcrypt useing in laravel and python
I am using dcrypt in larave with round 10 for password and now i want to access my site from django framework and want to check password from there when i hit with this sting 123456 it return me: $2y$10$leNO3kYBuqZ5I6gYJ4HyFe10PPC5zyjAN4xwLUWiOu1G7BC2Jwuj6 and when i hit from python password = 123456 hashed = bcrypt.hashpw(password, bcrypt.gensalt(10)) it return me this: $2b$10$KefWWC7IwzNOZjMg2YOT3eKJjAZLM/s84AOv0IH/QNEknMeIYMZWW How can i get same request ? -
django.db.utils.ProgrammingError: in DJango application
I am working with a Django application with Postgres Database. My models are as follows: from django.db import models from django.contrib.auth.models import User as UserModel from dynamicforms.mangers import TextQuestionManager, MCQManager, IntegerQuestionManager from django.db.models.fields.related import OneToOneRel from django.contrib.postgres import fields as postgres_fields Qtypes = [(1, "Multiple Choice Question"), (2, "Text Question"), (3, "integer Type Question")] COMPS = [(True, 'Yes'), (False, 'No')] SECTIONS = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)] class QuestionModel(models.Model): qtype = models.IntegerField(null=False, choices=Qtypes) text = models.TextField(max_length=500, null=False, blank=False) description = models.TextField(max_length=1000, null=True, blank=True) help_text = models.CharField(max_length=300, null=True, blank=True) is_compulsory = models.BooleanField(default=True, null=False, choices=COMPS) def __str__(self): return self.text class TextQuestionModel(QuestionModel): nextQ = postgres_fields.ArrayField(models.IntegerField(blank=True, null=True), null=True, blank=True) objects = TextQuestionManager() class MCQModel(QuestionModel): objects = MCQManager() class Meta: proxy = True class IntegerQuestionModel(QuestionModel): nextQ = postgres_fields.ArrayField(models.IntegerField(blank=True, null=True), null=True, blank=True) objects = IntegerQuestionManager() I made few changes to my schema.So i have to reset my DB.I reseted my DB and migrations and when im trying to run python manage.py makemigrations I am getting this error.I tried changing db and changing user and everything.I dont understand what made this error. Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace instance at 0x7fa990057998> Traceback (most recent call last): File "/opt/pycharm/helpers/pydev/_pydev_bundle/pydev_monkey.py", line 553, in … -
postgresql: FATAL: password authentication failed for user "douglas"
in first: sorry for this duplicate, but the others similar questions related for this issue always tell the same method to fix this problem, but did don't works for me.I trying to migrate a DB from sqlite to postgresql...so I type: sudo -u postgres psql postgres=# ALTER USER postgres WITH PASSWORD 'newpassword'; and the output return: "ALTER ROLE" but when I type "python manage.py migrate" I receive always the same error: django.db.utils.OperationalError: FATAL: password authentication failed for user "user" settings.py: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', ] 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', ] ROOT_URLCONF = 'site_.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'site_.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases """ DATABASES = { #'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), #} 'default': dj_database_url.config(default='postgres://localhost:5432/postgres_db_name'), } """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'douglas_db', 'USER': 'douglas', 'PASSWORD': 'vamointer', 'HOST': '127.0.0.1', 'PORT': '5432', } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators #DATABASES = {'default': dj_database_url.config(default='postgres://127.0.0.1:5432/postgres_db_name')} AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': … -
Django query optimisation: Get first and latest results
I have a Report model with a created date. I want to get the first and latest reports based on created date. For example, if we have following reports with created date R1 (2017-02-01) R2 (2017-01-02) R3 (2017-03-01) R4 (2017-01-31) R5 (2016-01-01) R6 (2017-03-04) if count=5 expected result should be [R5,R4,R1,R3,R6] if count=3 expected result should be [R5,R3,R6] Here is the solution I came up with. def get_reports(client, count=5): first = list(Report.objects.filter(client=client).order_by('created')[:1]) rest = list(Report.objects.filter(client=client).order_by('-created')[:count - 1]) rest.reverse() if first and first[0] in rest: return rest else: return first + rest It works but wants to know if there is a better way to do this. -
virtual env python 3.5 only finds django python 2.7
I have created python 3.5.2 virtual environment ("python --version" confirms that) but when i try to install django using "pip install django~=1.10.0" I get this message: Requirement already satisfied: django~=1.10.0 in /usr/local/lib/python2.7/dist-packages How can I get django version that agrees with the python version in my venv? -
How do i detect the current domain name in django?
I want to design my web application to serve two different front-end templates depending on what domain the user enter my django application. So if the user enter aaa.com, it would serve front-end from app AAA_USA, but if the user enter from aaa.co.my, it would serve front-end from app AAA_MY. What is the best way to do this? I was thinking of "detecting the current domain name" and then simply add an if-else statements in the View functions. These two domains will be pointing to the same Nameservers that contains my Django app. -
django url parameter has space,How to solve it?
I'm a newbie for program and study django now. I have one question. example: my product title: classic photo frame my url: url(r'^(.+)/$', products, name='products'), I open through url with www.xxx.com/classic photo frame/ it works,but the this url has space, I know it's not correct. I add - to parameter,such as classic-photo-frame. It works too. But this way, - will show in front-end page. How can I resolve? url shows /classic-photo-frame but the front-end page is classic photo frame Thank you. -
Issues with static files on Heroku when deploying a Django/Python App
I looked for a solution on stackoverflow before asking my question & I have been dealing with this bug for a while. I am not sure how to fix it. I already read the help section in Heroku, & it was absolutely not helpful. I would truly appreciate any advice/guidance. My issue is that I receive a not found status (404) on Heroku, despite the fact that the files are in the right file, & exist. I am not sure how to fix it. Below is my log: 2017-03-27T20:37:35.742277+00:00 heroku[router]: at=info method=GET path="/" host=websiteblue.herokuapp.com request_id=9e270735-dd53-435c-8d83-0006ca619283 fwd="75.72.178.101" dyno=web.1 connect=1ms service=61ms status=200 bytes=1713 protocol=https 2017-03-27T20:37:35.818665+00:00 heroku[router]: at=info method=GET path="/static/css/introduction.css" host=websiteblue.herokuapp.com request_id=50d359a4-c3a3-4781-bb7c-e9a952fb694e fwd="75.72.178.101" dyno=web.1 connect=0ms service=9ms status=404 bytes=301 protocol=https 2017-03-27T20:40:16.867973+00:00 heroku[router]: at=info method=GET path="/" host=websiteblue.herokuapp.com request_id=b978973d-9e58-4a22-815d-5f3205532386 fwd="75.72.178.101" dyno=web.1 connect=1ms service=3ms status=200 bytes=1713 protocol=https 2017-03-27T20:40:16.961348+00:00 heroku[router]: at=info method=GET path="/static/css/introduction.css" host=websiteblue.herokuapp.com request_id=2622be5f-dfe1-45a9-a838-28af2a526529 fwd="75.72.178.101" dyno=web.1 connect=1ms service=17ms status=404 bytes=301 protocol=https -
can't create local data base in python
when i'm try to apply migrate to create my locol db, python return a RubtimeError: maximum recursion depth exceeded while calling a Python object can you help me to solve that i'm on mac and use os x lion (10.7) -
Why am I receiveing 'no module named wagtail' error when I try to launch django app
I have an existing Django Project. I would like to use Wagtail with it. I have followed the instructions here: http://docs.wagtail.io/en/v1.9/getting_started/integrating_into_django.html However when I try to launch my app, I receive the following error message from uWSGI:- *** Operational MODE: preforking *** Traceback (most recent call last): File "./core/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/django/env/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup() File "/opt/django/env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/django/env/lib/python2.7/site-packages/django /apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/opt/django/env/lib/python2.7/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named wagtail unable to load app 0 (mountpoint='') (callable not found or import error) ImportError: No module named wagtail However I have installed wagtail. I found this https://github.com/wagtail/wagtaildemo/issues/32 Which suggested Please can you run pip freeze and paste the output here? I have run pip freeze, and this was the result: - Django==1.9.12 Pillow==3.0.0 Unidecode==0.4.20 Willow==0.4 argparse==1.2.1 assert-exists==0.0.0 backports.ssl-match-hostname==3.5.0.1 beautifulsoup4==4.5.3 caller-module==0.0.0 cp==0.0.0 distribute==0.7.3 django-appconf==1.0.1 django-autocomplete-light==3.2.1 django-compat==1.0.8 django-compressor==1.6 django-dual-authentication==1.0.0 django-hijack==2.0.1 django-htmlmin==0.8.0 django-ipware==1.1.2 django-mathfilters==0.3.0 django-modelcluster==3.0.1 django-taggit==0.22.0 django-treebeard==4.1.0 django-widget-tweaks==1.4.1 djangorestframework==3.6.2 evernote==1.25.1 html5lib==0.9999999 httplib2==0.9.2 not==1.7 oauth2==1.9.0.post1 olefile==0.44 pbr==1.8.1 public==0.0.0 publicsuffix==1.1.0 python-dateutil==2.2 pytz==2015.7 requests==2.13.0 setupfiles==0.0.0 simplejson==3.10.0 six==1.10.0 slackclient==1.0.5 stevedore==1.10.0 svn==0.3.36 uWSGI==2.0.11.2 url==0.1.5 virtualenv==13.1.2 virtualenv-clone==0.2.6 virtualenvwrapper==4.7.1 wagtail==1.9 … -
show a list of buyers that has contacted a rent
A rent can be contacted by many user to buy. I want to show the list of all users that has contacted a specific rent. Should i create a UserAPIView and show over there or show list of users in RentDetail? Which one is the best design? Here is my model and serializer class Rental(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=300, blank=False, null=False) phone_number = models.PositiveIntegerField(null=False, blank=False) class Contact(models.Model): buyer = models.ForeignKey(User) rental = models.ForeignKey(Rental, related_name="rent") phone_number = models.PositiveIntegerField(null=False, blank=False) buyer_choice = models.CharField(choices=BUYER_CHOICES, max_length=1, null=False, blank=False) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email',) class RentalSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') galleries = GallerySerializer(many=True) class Meta: model = Rental fields = ('__all__') class UserAPI(APIView): def get(self, request, format=None): """ List all the users """ reply = {} try: users = User.objects.all() reply['data'] = UserSerializer(users, many=True).data except: reply['data'] = [] return Response(reply, status.HTTP_200_OK) class RentAPIView(APIView): def get(self, request, token=None, format=None): """ Returns a list of rents (or just rent if token is given) """ reply = {} try: rents = Rental.objects.filter(user=request.user) buyer_id = self.request.query_params.get('buyer_id', None) if buyer_id: print ('buyer_id', buyer_id) rents = rents.filter(rent__buyer__id=buyer_id) if token: rent = rents.get(id=token) reply['data'] = RentalSerializer(rent).data else: reply['data'] = RentalSerializer(rents, many=True).data except Rental.DoesNotExist: return error.RequestedResourceNotFound().as_response() … -
Is it fine to handle complex string in url or better format it
I have data to be handled by urls.py. Those are strings, which have spaces comas and etc ALEKSEEV,%20%D0%A2%D1%83%D1%80%20%C2%AB%D0%9F%D1%8C%D1%8F%D0%BD%D0%BE%D0%B5%20%D1%81%D0%BE%D0%BB%D0%BD%D1%86%D0%B5%C2%BB So is it ok to handle such a string by complex regular expression, or is it better to get rid of all spaces and signs and make one more specific field in model for handling request? Why? -
Two signup form using django-allauth
I am striving since 2 day to develop two form using django-allauth. I still have no idea on how can i do this. I am not talking about form wizard. By two different signup form i mean, signup as developer and signup as normal user in same template. Developer signup form will have only one additional field and that is experties. If for one form then i would do the following way but how can i for two forms who has not same fields. ACCOUNT_SIGNUP_FORM_CLASS = 'pages.custom_sign_up_form.CustomSignupForm' class CustomSignupForm(forms.Form): def __init__(self, *args, **kwargs): super(CustomSignupForm, self).__init__(*args, **kwargs) def signup(self, request, user): user.save() Can anyone please enlighten me the process/workflow? -
Issue using Django to pass JSON to Javascript
I'm using Django to return a JsonResponse to a script that is supposed to handle JSON and get coordinates for me. There seems to be something wrong when I try and use the JSON information in the javascript. For example, if i try to use data.something , its undefined. Here is my View: def getTweets(request, tag): d = {'string': tag} req = tweets.objects.filter(tag = tag) data = serializers.serialize('json', req, fields=('coord')) data = JsonResponse(data, safe=False) print data return data And here is the part of the JS I am currently using: $('#searchButton').click(function(){ xmlhttp = new XMLHttpRequest(); var tag = document.getElementById('tagSearch').value; if(tag.substring(0,1) === '#'){tag=tag.substring(1,tag.length);} document.getElementById('tagSearch').value = ''; xmlhttp.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { var data = JSON.parse(this.response); var pinColor = ''+(Math.random()*0xFFFFFF<<0).toString(16); ........... So, I am using JSON.parse(this.response) to get this from Django, which returns a string. But as I said, something is seemingly wrong or I am completely missing how to access this. This is from my Django server console: "[{\"model\": \"visualize.tweets\", \"pk\": 1, \"fields\": {\"coord\": \"-76.958123, 38.827518\"}}, {\"model\": \"visualize.tweets\", \"pk\": 3, \"fields\": {\"coord ": \"-96.958123, 48.827518\"}}]" And, what I want to be able to do (or something similar): var coordString = point['coord']; var x …