Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
upgrade Django 1.9 to 2.0
upgrade Django 1.9 to 2.0 getting an error django.core.exceptions.ImproperlyConfigured: WSGI application 'society.wsgi.application' could not be loaded; Error importing module. setting.py WSGI_APPLICATION = 'society.wsgi.application' wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "society.settings") application = get_wsgi_application() Python 3.5, Django 2.0 -
Manager isn't available; 'auth.User' has been swapped for 'polls.User'
I have created a different version of the User model where there is no username field and I am now trying to implement a sign in feature, but I keep getting the error Manager isn't available; 'auth.User' has been swapped for 'polls.User' I have searched the rest of this site and tried to implement the feature beneath to fix the problem but to no avail. from django.contrib.auth import get_user_model User = get_user_model() Here is the rest of my files Views from django.http import HttpResponse from django.shortcuts import get_object_or_404, render, render_to_response, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from polls.forms import SignUpForm from django.contrib.auth import get_user_model User = get_user_model() @login_required def home(request): return render(request, 'home.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = None raw_password = form.cleaned_data.get('password1') user = authenticate(password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) forms from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') username = None class Meta: model = User fields = … -
Django login not showing errors
I know there are multiple questions like this around, but none of them contain a clear answer. I am using the default authentication from Django, but have trouble displaying something like 'Your username/password combination is incorrect'. Is it possible to fix this without making a custom view function? My urls.py looks like this: url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='mysite_login') Then my login.html has the following code: {% block content %} <section class="content"> <div class="container block"> <div class="row"> <div class="col-md-12"></div> <form action="{% url 'mysite_login' %}" class="form-control" method="post" accept-charset="utf-8"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field|addcss:'form-control' }} {% if field.help_text %} <small style="color: grey">{{ field.help_text|safe }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit" class="btn btn-dark">Login</button> <input class="form-control" type="hidden" name="next" value="{{ next }}"><br> </form> </div> </div> </div> </section> {% endblock %} So this all works, except for displaying the error messages. I've seen answers where you can write a custom view function and form to fix this, but I assume it should be also possible while using the build-in login functionality right? Thanks a lot. -
Can't install Django using pipenv for unknown reason (but can using pip)
I have no idea what is causing this issue, I have tried uninstalling and re-installing everything from scratch, and I still can't solve this after two days of trying. I could really use some expert help. Am I missing something fundamental here? On my desktop I am running Windows 10, on my laptop I am running Windows 7 (Professional, SP1). On desktop, I pipenv to install django==1.11, and pip freeze shows django==1.11 listed. On my laptop, use pipenv to install django==1.10, but pip freeze doesn't list django. When I check pipfile.lock, I see django listed in there. When I try to use django-admin startporject project, The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check th e spelling of the name, or if a path was included, verify that the path is correct and try again. This is the log from my laptop, so that you can see all the commands I've used (in case I've missed one): PS C:\Project> pipenv install django==1.11 Creating a virtualenv for this project. Using C:\Python27\python.exe to create virtualenv. Running virtualenv with interpreter C:\Python27\python.exe New python executable in C:\Project\Scri... xe Installing setuptools, pip, wheel...done. Virtualenv location: … -
ProgrammingError: ForeignKey already exists when running PyTest in Django project
I am running pytest on a Django-cookiecutter project + Stripe (using Dj-stripe), and running into a ProgrammingError. self = <django.db.backends.utils.CursorWrapper object at 0x10e8323c8> sql = 'ALTER TABLE "djstripe_charge" ADD CONSTRAINT "djstripe_charge_account_id_597fef70_fk_djstripe_account_id" FOREIGN KEY ("account_id") REFERENCES "djstripe_account" ("id") DEFERRABLE INITIALLY DEFERRED' params = () ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0x10b5fc668>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x10e8323c8>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: return self.cursor.execute(sql) else: > return self.cursor.execute(sql, params) E django.db.utils.ProgrammingError: constraint "djstripe_charge_account_id_597fef70_fk_djstripe_account_id" for relation "djstripe_charge" already exists ../../Envs/tracer/lib/python3.6/site-packages/django/db/backends/utils.py:85: ProgrammingError When pytest is running django_db_setup, it is erring- request = <SubRequest '_django_setup_unittest' for <TestCaseFunction 'test_clean_username_false'>>, django_db_blocker = <pytest_django.plugin._DatabaseBlocker object at 0x1079f3cc0> @pytest.fixture(autouse=True, scope='class') def _django_setup_unittest(request, django_db_blocker): """Setup a django unittest, internal to pytest-django.""" if django_settings_is_configured() and is_django_unittest(request): getfixturevalue(request, 'django_test_environment') > getfixturevalue(request, 'django_db_setup') I've dropped the test db a few times, but the error is the same - referencing that Stripe charge during db setup. My pytest.ini: [pytest] DJANGO_SETTINGS_MODULE=config.settings.test I'm trying to debug why this is getting created twice, however I'm hitting a roadblock on where to look. Any ideas? Thank you in advance for your help! -
HTTPError: HTTP Error 401: Invalid (legacy) Server-key delivered or Sender is not authorized to perform request. - Django push notifications
I can't send notifications to other devices like mobile phones with Django push notifications. I get an error saying : HTTPError: HTTP Error 401: Invalid (legacy) Server-key delivered or Sender is not authorized to perform request. -
python django deploy vs ruby on rails capistrano deploy
i'm learning Ruby on Rails. And i wrote a small app. now i want to deploy it to my domain. i don't want to make it live under heroku. so i bought a host package from digitalOcean. i used a couple deployment tutor, but no luck. it doesn't show my homepage. i like Ruby on Rails so much. especially approaching to database. but deploying is very hard, if you don't want to pay for it a company like heroku. now, i'm thinking another choices. i love osx and i want to code there. because of this, i don't think to learn c# and .net. python is warm to me. so, is the deploying of python django easier than RoR deployment, like html/ccs/js or lamp sites? thank you all! -
Refresh page without reload. Wagtail
Where can i put ajax get data code in Wagtail? I have following page model: class ScreencastPage(Page): content_panels = Page.content_panels + [ InlinePanel( 'groupstage_screencast_relationship', label="Choose Teams", panels=None, max_num=2), ] parent_page_types = ['home.HomePage'] def matches(self): matches = [ n.match for n in self.groupstage_screencast_relationship.all() ] return matches And my template: {% for spiel in page.matches %} {% if forloop.first == forloop.last %} <div id="fullscreen"> <ul class="ulup"> <li class="logo_bg first_team">{% image spiel.team_1.team_logo width-400 class="logo" %}<p>{{spiel.team_1.title}}</p></li> <li class="first_team_score">{{ spiel.team_1_total_score }}</li> <li class="colons">:</li> <li class="second_team_score">{{ spiel.team_2_total_score }}</li> <li class="logo_bg second_team">{% image spiel.team_2.team_logo width-400 class="logo" %}<p>{{spiel.team_2.title}}</p></li> </ul> </div> {% endif %} {% endfor %} I started writing js. Just exaple: $(document).ready(function() { setInterval(function(){ $.ajax({ type: "GET", url: "/presentation", success: function(data) { $(".first_team_score").update(data.team_1_total_score); $(".second_team_score").update(data.team_2_total_score); } }) }, 10000); }); The idea is that the page will automatically update the value of <li class="first_team_score">{{ spiel.team_1_total_score }}</li> and <li class="second_team_score">{{ spiel.team_2_total_score }}</li> without reloading the page. I found here great example, but they using view.py We also need to write a new view.py or have wagtail some method for that? -
Override in the widget attributes the max_length set on the Model
In the Model I set the maxlength of the field: short_description = models.CharField(max_length=405) In the ModelForm in the widget attributes I set minlength an maxlength: widgets={ 'short_description': TextareaWidget(attrs={'minlength': 200, 'maxlength': 400}), .... } The issue in the HTML the minlegth is from the widget, but maxlength is still taken from the model(405 instead of 400). I want the widget attribute to overwrite the model attribute. -
Owner of the data and superuser should only be able to update the data using CBV
This is my UpdateView. As i have just started django. I am a newbie views.py @method_decorator(login_required, name='dispatch') class ProductUpdateView(UpdateView): fields = ('product_name', 'product_cost') model = Product I have created a superuser and a user. Superuser should be able to update all the product of both his and everyone else's but user should be only be able to update his product only. urls.py urlpatterns = [ url(r'^product/(?P<pk>\d+)/update/$', login_required(ProductUpdateView.as_view()), name='product_update'), ] I have a created a product using superuser, which has pk = 1. When i login with some user (Which not superuser) and visit the above url. This user is able to update superuser's product. models.py class Product(models.Model): product_name product_cost # This two fields and created_by created_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name="Product", null=True) Is there any way that own of the data can update that data and if user tries to access someone else's data it should Http404. -
When using ajax with django views, when should I use a method of GET and when should it be POST?
I'm able to accomplish the same task with either--I only need to make sure that if the ajax method is get, then my view needs to handle the get and if a POST, that the view handles a post. Given this, when do I use a GET and when do I use a POST? $.ajax({ method: "????", url: $endpoint, data: $buttonData, success: handleSuccess, error: handleError, }) class MyAjaxView(View): def ???(self, request, *args, **kwargs): -
SyntaxError: Generator expression must be parenthezised / python manage.py migrate
I'm really new in programming and I wanted to follow the Djangogirls tutorial, but I'm stucked now. In the tutorial, I am here: To create a database for our blog, let's run the following in the console: python manage.py migrate (we need to be in the djangogirls directory that contains the manage.py file). If that goes well, you should see something like this: ... There is no option to fail in the tutorial but I have an error message: (myvenv) C:\Users\Julcsi\djangogirls> python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\Users\Julcsi\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 723, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_remove File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\contrib\admin\__init__.py", line 4, in <module> from django.contrib.admin.filters import ( File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\contrib\admin\filters.py", line … -
Floatformat don`t work
I`m getting started using template built in Django. I want to show variable with 3 value after dot but it doestn work. Code: {% assign zmienna = 9.7567 %} {{zmienna|floatformat:2}} Effect: 9.7567 What I do wrong? -
Django-cms: How to add side navigation
I am using latest django-cms(3.5.0), i have installed it through djangocms-installer. And now i want to add extra navigation tree, since i don't want it being nested inside Main navigation. I want to add it like this: https://imgur.com/2IXwgnY How can i add it? The following apps are installed: INSTALLED_APPS = ( 'djangocms_admin_style', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.staticfiles', 'django.contrib.messages', 'cms', 'menus', 'sekizai', 'treebeard', 'djangocms_text_ckeditor', 'filer', 'easy_thumbnails', 'djangocms_column', 'djangocms_file', 'djangocms_link', 'djangocms_picture', 'djangocms_style', 'djangocms_snippet', 'djangocms_googlemap', 'djangocms_video', 'dslendavasite', ) -
Value error in Django because the view request.GET or request.POST can't catch values from javascript
I have a quiz app and there are lots of interactions between JavaScript in templates and django views. Normally, on decent enough internet connection and less traffic the code works as it is supposed to. But as soon as the internet is slow and traffic is high (ie. 20 or so people are taking a quiz at the same time) . Django views stop catching values sent from forms in template Here is an example: Template code <form action='{% url "QuestionsAndPapers:EvaluateTest" %}' method='post' id ='finishForm'> {%csrf_token%} <input type="text" name="timeTaken" value="" class='hidden' /> <button type="submit" id='testsub' value="{{te_id}}" class="btn btn-default text-center" name="testSub" onclick="formClick()" >Submit Test</button> </form> Django View: def evaluate_test(request): user = request.user me = Studs(user) if 'testSub' in request.POST: # get values of test id and total test time try: test_id = request.POST['testSub'] test_id = int(test_id) Now the problem is majority of times the template successfully returns {{te_id}} variable but when traffic is high and internet is slow evaluate_test function can't catch the {{te_id}} variable and it throws an error ValueError: invalid literal for int() with base 10: The problem is this error is not reproducible. -
select backward associated in django
I'm wrinting a Django project. In courses/models.py class Category(models.Model): title = models.CharField(max_length=50) class Language(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=50) I want to get list of all Category and then loop through each Language of specified category. class Courses(ListView): template_name = 'courses/index.html' model = Course context_object_name = 'courses' def get_context_data(self, **kwargs): context = super(Courses, self).get_context_data(**kwargs) categories = Category.objects.all() context['categories'] = categories return context in template courses/index.html I want to show the list of languages based on category {% for category in categories %} {{ category.title }} <li>lis of languages in this category</li> {% endfor %} How to loop on backward associated data? -
Where should a Django homepage template and view exist in a large-scale project?
On a large-scale Django project, where should the homepage template and view exist within the project structure? In its own app (ex: homepage app)? Some other app (ex: accounts)? At the project-level putting the template in a "templates" directory and the view somewhere? Somewhere else? Is there a most frequent answer to this question? Definitions: Large-scale is defined as let's say 15 apps The homepage content is mostly static now, with plans to get more dynamic as the project evolves Assumption: project structure strategy is dependent on the size of the project. -
Django Axes Does not block Custom Login Page
I succesfully installed Django Axes in my app and can block my admin page after a certain amount of logins INFO:axes.watch_login:AXES: Repeated login failure by {user: 'admin', ip: '127.0.0.1', user-agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5', path: '/en/login/'}. Count = 10 of 10 WARNING:axes.watch_login:AXES: locked out {user: 'admin', ip: '127.0.0.1', user-agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5', path: '/en/login/'} after repeated login attempts. Unfortunately the Custom Login Page does not get blocked. It counts up the login attempts, too, but when it says, it gets blocked, I still can access the site. Do I need another trigger to block that, too? I didn't find anything like "is_blocked()" or sth. views.py class LoginView(FormView): template_name = "account/login.html" template_name_ajax = "account/ajax/login.html" form_class = LoginUsernameForm form_kwargs = {} redirect_field_name = "next" @method_decorator(sensitive_post_parameters()) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, *args, **kwargs): return super(LoginView, self).dispatch(*args, **kwargs) def get(self, *args, **kwargs): if is_authenticated(self.request.user): return redirect(self.get_success_url()) return super(LoginView, self).get(*args, **kwargs) def get_template_names(self): if self.request.is_ajax(): return [self.template_name_ajax] else: return [self.template_name] def get_context_data(self, **kwargs): ctx = super(LoginView, self).get_context_data(**kwargs) redirect_field_name = self.get_redirect_field_name() ctx.update({ "redirect_field_name": redirect_field_name, "redirect_field_value": self.request.POST.get(redirect_field_name, self.request.GET.get(redirect_field_name, "")), }) return ctx def get_form_kwargs(self): kwargs = super(LoginView, self).get_form_kwargs() kwargs.update(self.form_kwargs) … -
django and bootstrap modal ajax get data not working
Good day everyone. I'm trying to implement bootstrap modal for the first time in Django 1.11.6 under python 3. I'm using postgresql too. My Model class DentalProcedures(models.Model): id = models.AutoField(primary_key=True) patient = models.ForeignKey(PatientInfo, on_delete=models.CASCADE, null=True, blank=True) proc_date = models.DateField(null=True, blank=True) proc_tooth_no = models.CharField('Tooth No./s', max_length=10, null=True, blank=True) procedure = models.CharField('Procedure', max_length=200, null=True, blank=True) My Modal Form <form id="procedureForm"> {{form.as_p}} {% csrf_token %} <h2>{{ mypk }}</h2> <input type="hidden" name="patient" value="{{ mypk }}" id="id_patient"> <div id="modalTreatment" class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <input id="saveProcedure" type="submit" value="Save" class="btn btn-primary" /> </div> </form> My JS $(document).ready(function(){ $('#saveProcedure').click(function(e){ // e.preventDefault(); $.ajax({ headers: {'X-Requested-With': 'XMLHttpRequest'}, type:"GET", url: "/", cache: false, data: { tooth: $('input[name="proc_tooth_no"]').val(), date: $('input[name="proc_date"]').val(), proc: $('input[name="procedure"]').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken').val() }, success : function(data) { alert("congrats!"); }, error: function(jqXHR, exception){ var msg = ''; if (jqXHR.status === 0) { msg = 'Not connect.\n Verify Network.'; } else if (jqXHR.status == 404) { msg = 'Requested page not found. [404]'; } else if (jqXHR.status == 500) { msg = 'Internal Server Error [500].'; } else if (exception === 'parsererror') { msg = 'Parse error.'; msg = 'Requested JSON parse failed.'; } else if (exception === 'timeout') { msg = 'Time out error.'; } else if (exception === 'abort') … -
Multi-database routing with multiple custom database admins
I am trying to use multiple database with custom admin for database. I am using routing for this. When i leave my default database empty. It shows error settings.DATABASES is improperly configured. Please supply the ENGINE value. But on filling details in default database it works fine as it uses default settings for both the urls. Project settings.py 'default': { }, 'users': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'users', 'USER': '****', 'PASSWORD': '****', 'HOST': 'localhost', 'PORT': '5432', }, 'rsa': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'rsa', 'USER': '****', 'PASSWORD': '****', 'HOST': 'localhost', 'PORT': '5432', }, DATABASE_ROUTERS = ['antef.router.DBRouter'] DATABASE_APPS_MAPPING = { 'login': 'users', 'rsa': 'rsa' } Project urls.py from django.contrib import admin from django.urls import path, include admin.autodiscover() urlpatterns = [ path('login/', include('login.urls')), path('rsa/', include('rsa.urls')), ] Project routers.py from django.conf import settings class DBRouter: def db_for_read(self, model, **hints): """"Point all read operations to the specific database.""" return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label, None) def db_for_write(self, model, **hints): """Point all write operations to the specific database.""" return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label, None) def allow_relation(self, obj1, obj2, **hints): """Allow any relation between apps that use the same database.""" db_obj1 = settings.DATABASE_APPS_MAPPING.get(obj1._meta.app_label) db_obj2 = settings.DATABASE_APPS_MAPPING.get(obj2._meta.app_label) if db_obj1 and db_obj2: if db_obj1 == db_obj2: return True else: return False return None def allow_migrate(self, db, app_label, … -
What is '_get_val_from_obj' mechanic does?
I am new to tooling job. Currently my favorite package in Django is outdated and seems on one care by now. Therefore I would like to study it. Problem: https://github.com/philippbosch/django-geoposition/issues/100 Traceback (most recent call last): File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sarit/.pyenv/versions/3.6.4/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view return self.dispatch(request, *args, **kwargs) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch response = self.handle_exception(exc) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception self.raise_uncaught_exception(exc) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch response = handler(request, *args, **kwargs) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/mixins.py", line 22, in create headers = self.get_success_headers(serializer.data) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 537, in data ret = super(Serializer, self).data File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data self._data = self.to_representation(self.instance) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 504, in to_representation ret[field.field_name] = field.to_representation(attribute) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/fields.py", line 1858, in to_representation return self.model_field.value_to_string(obj) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/src/django-geoposition/geoposition/fields.py", line 50, in value_to_string value = self._get_val_from_obj(obj) AttributeError: 'GeopositionField' object has no attribute '_get_val_from_obj' Official Docs: https://docs.djangoproject.com/en/2.0/releases/2.0/ Field._get_val_from_obj() is removed. Question: How to solve this error? def value_to_string(self, obj): value = self._get_val_from_obj(obj) return … -
When posting to a Django form, are all fields posted?
I'm trying to write a test for a form to simulate the situation in which I'd like to update just one field. Here is the test: from django.test import TestCase from django.forms.models import model_to_dict class FamilyDemographicsUpdateTest(TestCase): def test_update_phone_types_with_fields_from_family_factory(self): # Create a family for which the employee uses an iPhone family = FamilyFactory(employee_phone_type=Family.IPHONE) url = reverse('dashboard:family', kwargs={'pk': family.id, 'tab': 'family-demographics'}) # TODO: This doesn't work because the FamilyFactory generates invalid form data. Fix that. data = model_to_dict(instance=family, fields=FamilyDemographicsForm.base_fields) form = FamilyDemographicsForm(data=data) after which I drop into the debugger with import ipdb; ipdb.set_trace(). It is here that I notice that the form has errors: ipdb> form.errors {'employee_email': ['This email is already taken.']} This can be traced back to the Family model on which the form is based. The form is a ModelForm: class FamilyDemographicsForm(forms.ModelForm): class Meta: model = Family The view is based on Django's generic UpdateView: class FamilyUpdate(SuccessMessageMixin, DashboardAccessMixin, UpdateView): template_name = 'families/edit.html' model = Family success_message = "Family was updated successfully." def get_form_class(self, **kwargs): tab = self.kwargs['tab'] if tab == 'family-demographics': return FamilyDemographicsForm and the corresponding Family object has a clean() method which is triggering this error (in class Family(models.Model)): def clean(self): if self.employee_email: db_user = User.objects.filter(username=self.employee_email).first() if db_user and … -
Chrome Mobile does not display checkbox
My website's register page has two checkbox inputs located at the bottom. On every browser I have tested on, there has been no issue. However, a user recently brought to my attention that these checkbox inputs are not displayed at all from their mobile device. I checked this on my Samsung Galaxy S7, and confirmed this finding. They do appear on my iPad and other Apple devices. Why are no checkbox inputs showing up on certain mobile devices? -
Django Messages not working when I try display error about existing user/email
In my Django project I want to use Django Message ( from django.contrib import messages) to display error when user or email exist. Unfortunately my views not working. HTML: {% for message in messages %} <p>{{ message }}</p> {% endfor %} views.py def account_signup(request): if request.method == 'POST': nick = request.POST['nick'] email = request.POST['email'] password = request.POST['password'] user_model = get_user_model() if user_model.objects.filter(username__iexact=nick).exists(): data = {'is_taken_nick': nick} messages.warning(request, 'Please correct the error below.') return render(request, "account/account_signup.html", data) if user_model.objects.filter(email__iexact=email).exists(): messages.warning(request, 'Please correct the error below.') data = {'is_taken_email': email} return render(request, "account/account_signup.html", data) user = User.objects.create_user(username=nick, email=email, password=password) user.save() return HttpResponse(status=202) else: """Return template with sign up page.""" return render(request, "account/account_signup.html") Thanks in advance! -
Linking up CSS (and static files in general) to html in Django
My html file isn't reading my css file - I've tried searching for all related questions on this issue, but still can't get the css file to be read. Here's what I have: settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) Beginning of index.html {% load staticfiles %} <!DOCTYPE html> <html leng="en"> <head> <title>Test</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap- theme.min.css"> <link rel="stylesheet" href="{% static 'css/main.css' %}" /> </head> My "static" and "templates" folder are on the same level, and main.css is at static/css/main.css