Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django acts like user is logged in but isn't
I have an AJAX login in my Django project. The ajax_login view gets POST, authenticate user and returns JsonResponse. Everything seems to work correct but the user isn't actually logged in. The weird is that in the view, I'm testing whether the user is logged in and they are. VIEW @csrf_exempt def ajax_login_(request): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username,password=password) if user: if user.is_authenticated(): print 'IS LOGGED IN' #THIS IS BEING PRINTED INTO CONSOLE SO USER IS LOGGED IN return JsonResponse({'status':0}) return JsonResponse({'status':1}) AJAX $(document).ready(function () { $('.login-form').find('.submitButton').click(function (e) { var next = $(this).closest('.login-form').find('input[name="next"]').val(); var password = $(this).closest('.login-form').find('#id_password').val(); var username =$(this).closest('.login-form').find('#id_username').val(); e.preventDefault(); var errors = 0; if (username == '') { $('#id_username_required').show(); errors += 1; } else { $('#id_username_required').hide(); } if (password == '') { $('#id_password_required').show(); errors += 1; } else { $('#id_password_required').hide(); } if (errors == 0) { $.ajax({ url: '/ajax/login/', type: 'post', data: { 'password': password, 'username': username, }, success: function (data) { if (data.status == 0) { window.location.reload(); } else { $('.login-modal-credentials-incorrect').show(); return false; } } }); } }) }); Can't figure out where is the problem. It suddenly stopped working. -
how the formset worksin django
I want to display a single form two times so i use formset. it display the form twice. but how to use formset validation? here is my code def add_result(request): if request.method == 'POST': ArticleFormSet = formset_factory(ResultForm, extra=2) form=ArticleFormSet(request.POST) if form.is_valid(): team=Team.objects.all() return HttpResponseRedirect('/success/') else: team=Team.objects.all() ArticleFormSet = formset_factory(ResultForm, extra=2) variables = RequestContext(request, {'ArticleFormSet': ArticleFormSet}) return render_to_response('add_result.html',variables,) -
Django default password encryption algorithm pbkdf2-sha256 how to use java to achieve
Encrypted password for example: how to use Java pbkdf2_sha256$15000$ZdYJKwuyheny$6pZJnPwX5wk6yGOtNFrz4nu3ePtkdURtmqiXwI/agFM= to achieve it? As the old app interface is also Python development, and now migrate to Java, but can not achieve Python password algorithm -
Django slice string in template doesn't work
I'm trying to slice my string but it doesn't work. It works perfectly on other variables but with this one it does nothing. {{b.rec_company|slice:":2"}} -
Dynamically creating models in Django
I want to create many models based on an abstract one, but with different default values for the fields. def get_model(name): class AbstractModel(models.Model): field1 = models.CharField(max_length=100, default=name) class Meta: abstract = True return AbstractModel class MyModel(get_model('MyModel')): pass What are disadvantages of the approach presented above? Is there any better way? -
Django cms how to debug from server the 404 custom view?
I've a problem with my custom editable 404 page (using django-cms 3.1.4) which return a 404 OK or 200 OK but never a 404 NOT FOUND. I don't find a single working solution (the second problem is that I've to manage the multi language as well)and then I would love to debug myself step by step my view. But as you know you can't access the 404 custom template on local with debug=true. Then I will have to check my variables directly from the development server. I was thinking about using PDB, but you need a console. In my case I have gunicorn running in background, supervised by supervisorctl. I wanted to use the logging command, even ready to store it in a file.log but when I do my declaration in settings.py I can't access the log from my 404 custom_page view. Here is my view, trigger from handler404: def custom_page_not_found(request): current_site = Site.objects.get_current() cms_page_not_found = _get_page_by_untyped_arg('404', request, current_site) if cms_page_not_found: language = get_language() request._current_page_cache = cms_page_not_found slug = '' with i18n.force_language(language): if not cms_page_not_found.is_home: slug = cms_page_not_found.get_path(language, True) or cms_page_not_found.get_slug(language, True) response = details(request, slug) try: response.render() response.status_code = 404 return response except: pass return page_not_found(request) I'm really out … -
How to use django template in a Dojo widget's templateString?
I have a dojo widget created. It uses a HTML template string to show a block. I need to use django template logics to use within the template string. say, var template = "<div>"+ "{% if ${showHello}%}"+ "Hello"+ "</div>" and My widget declaration, TemplatedListItem = declare( [ListItem, TemplatedMixin], { label: "My label", variableHeight: true, templateString: template } ); But, django template is showing in its raw form. Thanks in advance. -
Multiple databases in django with migrations
I have two databases configured, one for all but one tables, table, which I have in the second database, database2. I store data, and retrieve data perfectly without using any router, just the 'using' attribute on the save and the get. I was upgrading our app to django 1.8 a while ago, and it seemed to be working, table in database2 doesn't change that often, but it has been working ok since the upgrade. But now I need to make a change to table in database2. So I try manage.py migrate table --database database2. The migration seems to take, but I get an error in the end. RuntimeError: Error creating new content types. Please make sure contenttypes is migrated before trying to migrate apps individually. I've been trying to add contentypes and auth as fake migrations in database2, but I still get the error. Will adding a router make it go away? Are there any other ways? Thanks! -
Force User to Provide Profile Before Saving in Django Admin
Am trying to force a user to provide a profile before they are saved from the django admin. here is my profile model class UserProfile(models.Model): user=models.OneToOneField(AUTH_USER_MODEL,related_name='profile',primary_key=True) #other fields def get_user_info(user): return UserProfile.objects.get(user=user) @receiver(post_save, sender=AUTH_USER_MODEL) def create_profile_for_new_user(sender, created, instance, **kwargs): if created: profile = UserProfile(user=instance) profile.save() Am using authtools so the user profile sender is AUTH_USER_MODEL. If I add a new user from within admin,they are saved even if they have not provided or filled in the profile. I want to prevent them from being saved until they fill in the profile fields. Any insights on how to do this? Here is my admin.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import PasswordResetForm from django.utils.crypto import get_random_string from authtools.admin import NamedUserAdmin from authtools.forms import UserCreationForm User = get_user_model() class UserCreationForm(UserCreationForm): """ A UserCreationForm with optional password inputs. """ def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['password1'].required = False self.fields['password2'].required = False # If one field gets autocompleted but not the other, our 'neither # password or both password' validation will be triggered. self.fields['password1'].widget.attrs['autocomplete'] = 'off' self.fields['password2'].widget.attrs['autocomplete'] = 'off' def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = super(UserCreationForm, self).clean_password2() if bool(password1) ^ bool(password2): raise forms.ValidationError("Fill out both fields") return password2 … -
How to access Django App from NodeJS deployment in EC2 container
I have a Django App which is my Machine Learning server. It is used to serve real-time predictions to my NodeJS App. I am running this application in Amazon EC2 container and the web-server in Nginx. I don't want to expose the Django application to the outside world but only to the Node.js server. I have NodeJS application that running in a EC2 container and accesses the Django application like request.post('http://localhost:8000/polls/distance', { form: { _id : JSON.stringify(req.user._id), "arr": JSON.stringify(arr) } }, (err, body, response) => { if (err) throw err; else { console.log(response); res.status(200).send(response); } }); My Django app is running locally at address http://127.0.0.1:8000. This works fine on my local system but when I try to run this on my EC2 instance it doesn't work. I have tried the command 'python manage.py runserver 0:8000' and then tried accessing it via ipaddress:port notation and it loads by saying bad request. I will close this port on my EC2 instance once it works so that nobody from outside can access it. Because if it cannot work in a browser it will also not work in the request module for Node.js that's what my understanding is. I have already referred a lot … -
How to set minimum number of characters for user password in django-allauth
I want to change the ACCOUNT_PASSWORD_MIN_LENGTH in django-allauth. I tried ACCOUNT_PASSWORD_MIN_LENGTH = 5 in settings.py and it is not working, Django is still saying that I need to enter 8 characters, like it is by default. Here is my settings.py file: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'taggit', 'django_summernote', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'user_account', 'widget_tweaks', ] SITE_ID = 1 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 = 'project_blog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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 = 'project_blog.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'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators 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.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Django-allauth AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, … -
Django URL mapping - NameError: name X is not defined
[A similar question was asked, but not marked as answered, here. I considered continuing that thread but the website told me I'm only supposed to post an answer, so it seems I have to start a new topic.] I'm trying to follow this tutorial and I'm having problems with the URL mapping. Specifically with the part described as "So best practice is to create an “url.py” per application and to include it in our main projects url.py file". The relevant, I hope, part of the folder structure, which arose by following steps of the tutorial to the letter (if possible; usage of the 'patterns' module was impossible for example) and using Django 1.10 is the following: myproject/ myapp/ urls.py views.py myproject/ urls.py The myproject/urls.py is as follows: from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() from myapp.views import hello urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^myapp/', include(myapp.urls)), ] The myapp/urls.py is as follows: from django.conf.urls import include, url urlpatterns = [ url(r'^hello/', myapp.views.hello), ] The myapp/views.py is as follows: from django.shortcuts import render def hello(request): return render(request, "hello.html", {}) However, running 'python manage.py runserver' results in the following error: url(r'^myapp/', include(myapp.urls)), NameError: name 'myapp' is not defined INSTALLED_APPS in … -
How to Python Code on Interpreter Startup in Virtualenv?
I want to execute code after the python interpreter has started. We use virtualenv and up to now we had a file called sitecustomize.py which got executed during interpreter start up. The sitecustomize.py was part of our project. We use the Django definition of this term: It is a small python module which only holds config and nearly no code: Django's Definition of "Project" Unfortunately some linux distros (Ubuntu) provide a global sitecustomize, and our per virtualenv sitecustomize does not get loaded. Question How to run Python code on interpreter startup in a virtualenv? This code should be executed even if the interactive interpreter gets started. Goal vs Strategy I don't care if this hook is called "sitecustomize" or different :-) -
Django pass template name as parameter through command line
A list of templates are in Django project process_1.html process_2.html Requirement is to pass the template name as parameter from commandline and invoke it Example command to invoke the template manage.py runserver process_1.html -
GroupBy Serializer
I have the following situation class MyModel(models.Model): key = models.CharField(max_length=255) value = models.TextField(max_length=255) category = models.CharField(max_length=4) mode = models.CharField(max_length=4) the fields key, category and mode are unique together. I have the following objects: m1 = MyModel(key='MODEL_KEY', value='1', category='CAT_1' mode='MODE_1') m2 = MyModel(key='MODEL_KEY', value='2', category='CAT_1' mode='MODE_2') m3 = MyModel(key='MODEL_KEY', value='1', category='CAT_2' mode='MODE_1') m4 = MyModel(key='MODEL_KEY', value='2', category='CAT_2' mode='MODE_2') I want to expose an API that will group by key and category so the serialized data will look something like this: { "key": "MODEL_KEY", "category": "CAT_1" "MODE_1": { "id": 1, "value": "1" } "MODE_2": { "id": 2, "value": "2" } }, { "key": "MODEL_KEY", "category": "CAT_2" "MODE_1": { "id": 3, "value": "1" } "MODE_2": { "id": 4, "value": "2" } } Is there any way of doing this in django rest framework with ModelSerializer. -
django.http.JsonResponse return json data in wrong format
I want to return the queryset in json format, and I use the JsonResponse as the following: def all_alert_history(request): ''' get all all alert history data ''' all_data_json = serializers.serialize('json', LatestAlert.objects.all()) return JsonResponse(all_data_json,safe=False) but the browser shows like this: "[{\"fields\": {\"alert_name\": \"memory usage\", \"alert_value\": 83.7, \"alert_time\": \"2016-11-08T06:21:20.717Z\", \"alert_level\": \"warning\", \"alert_rule\": \"warning: > 80%\"}, \"model\": \"alert_handler.latestalert\", \"pk\": \"xyz.test-java.ip-10-0-10-138.memory.percent\"}]" I replace the JsonResponse with HttpResponse : def all_alert_history(request): ''' get all all alert history data ''' all_data_json = serializers.serialize('json', LatestAlert.objects.all()) return HttpResponse(all_data_json, content_type='application/json') and the browser shows like this: [{"fields": {"alert_name": "memory usage", "alert_value": 83.7, "alert_time": "2016-11-08T06:21:20.717Z", "alert_level": "warning", "alert_rule": "warning: > 80%"}, "model": "alert_handler.latestalert", "pk": "xyz.test-java.ip-10-0-10-138.memory.percent"}] so, why does the \ appears when I use the JsonResponse but disappear when use the HttpResponse? django version:1.8 -
Django View with ForeignKey model
I've got following in the models.py: class ArticleCategory(models.Model): category_name = models.CharField("Category", max_length=200, unique=True) slug = models.SlugField(null=True, blank=True, unique=True) def get_data(self): return { "id": self.pk, "category_name": self.category_name, "slug": self.slug, } class Article(models.Model): category = models.ForeignKey(ArticleCategory) ... def get_data(self): return { "id": self.pk, ... } views.py: def articles(request, *args, **kwargs): context = { 'categories': ArticleCategory.objects.all(), 'articles': Article.objects.filter(category__id=2) } return render(request, 'wellness.html', context) And everything works fine. However, I want category__id to be dynamic, so I'm changing function to be def articles(request, id, *args, **kwargs) and to 'articles': Article.objects.filter(category__id=id) Seems like it was working with previous projects for me, but now it throws that error every time I try to set up such behavior (tried id, slug, category_name): Exception Type: TypeError Exception Value: articles() takes at least 2 arguments (1 given) Exception Location: .../env/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py in _wrapped_view, line 23 Maybe something with urls.py? from django.contrib.auth.decorators import login_required ... urlpatterns = [ ... url(r'^wellness$', login_required(articles), name='wellness'), ... ] -
Django KeyError when trying to format foreignkey
I'm getting the following error when trying to create a filepath filepath = '{comp}/utils/locndb/{vehdir}.{filename}'.format(comp,vehdir, filename) KeyError: 'comp' I don't know how to extract the string from a one-to-many foreignkey field extra.py def get_file_path(vehicle, filename): filepath = '' vehdir = vehicle.vehid print vehdir comp = getattr(vehicle.company, 'user', None) print comp filepath = 'optiload/{comp}/utils/locndb/{vehdir}.{filename}'.format(comp,vehdir, filename) print filepath return filepath views.py @login_required def loadlocndb(request): if request.method == "POST" and request.FILES['locndb']: pks = request.POST.getlist("update") selected_objects = Vehicle.objects.filter(pk__in=pks) vlist = [] for i in selected_objects: vlist.append(i) locnfile = request.FILES['locndb'] fs = FileSystemStorage() filename = fs.save(locnfile.name, locnfile) filename = get_file_path(i, filename) uploaded_file_url = fs.url(filename) return render(request, 'portal/loadlocndb.html',{"vlist":vlist, "uploaded_file_url": uploaded_file_url}) models.py # Create your models here. class UserProfile(models.Model): # This line is required. Links UserProfile to a User model instance. user = models.OneToOneField(User) # The additional attributes we wish to include. compName = models.CharField(max_length = 20) milkco = models.IntegerField() # Override the __unicode__() method to return out something meaningful! def __unicode__(self): return self.user.username class Vehicle(models.Model): vehid = models.CharField(max_length = 10) company = models.ForeignKey(UserProfile, default = 1) #depot = models.ForeignKey(Depot, default = 1) locndb = models.FileField(upload_to='optload/', default= "setting.MEDIA_ROOT/locndb/LocnDB.csv") class Meta: db_table = "vehicle" def __unicode__(self): return self.vehid I want to import and save a file to the filepath … -
convert requests.models.Response to HttpResponse
In my Django project, I need to get/post some data to a third-party url in my view, and redirect to the web page it provides. For example, I can simply do something like class TestView(TemplateView): def get(self, request, *args, **kwargs): data = { 'order_id': 88888, 'subject': 'haha', 'rn_check': 'F', 'app_pay': 'T', } url = 'http://some-third-party-api-url?order_id=88888&subject=haha&...' return HttpResponseRedirect(url) However I want to use this third-party api as a wrapped SDK , like class TestView(TemplateView): def get(self, request, *args, **kwargs): from sucre.alipay_sdk.base import Alipay from sucre.alipay_sdk import alipay_config from django.http import HttpResponse alipay = Alipay(alipay_config) data = { 'order_id': 88888, 'subject': 'haha', 'rn_check': 'F', 'app_pay': 'T', } '''alipay api is wrapped in a sdk''' '''and return a requests.models.Response instance''' result = alipay.api('pay', data) return HttpResponse(result) and the api code: def api(self, service, data): ''' some logics here ''' import requests response = requests.get(url, data=data) return response But seems HttpResponse(result) is not the correct way to convert a requests.models.Response instance to HttpResponse... The layout is bad, and some more encoding issues, etc...Is there a correct way to convert requests response to Django HttpResponse? -
Graphene-django - How to catch response of query?
I use django and django graphene for make a graphql API. In the view of my application, I use reactJS and react-bootstrap-table. React-bootstrap-table expects that I pass it an object array but does not support nested objects. I created query in my schema.py: class ApplicationNode(DjangoObjectType): class Meta: model = Application filter_fields = ['name', 'sonarQube_URL'] interfaces = (relay.Node,) class Query(ObjectType): application = relay.Node.Field(ApplicationNode) all_applications = DjangoFilterConnectionField(ApplicationNode) The answers to these queries are JSON nested objects like this: { "data": { "allApplications": { "edges": [ { "node": { "id": "QXBwbGljYXRpb25Ob2RlOjE=", "name": "foo", "sonarQubeUrl": "foo.com", "flow":{ "id": "QYBwbGljYXRpb45Ob2RlOjE=", "name": "flow_foo" } } }, { "node": { "id": "QXBwbGljYXRpb25Ob2RlOjI=", "name": "bar", "sonarQubeUrl": "bar.com" "flow":{ "id": "QXBwbGljYXRpb26Ob2RlOjA=", "name": "flow_bar" } } } ] } } } I have to put them flat before giving them to React-bootstrap-table. What is the better way, intercept the results of graphene-django queries to put them flat or make this job in ReactJS view? If the first way is better, how to intercept the results of graphene-django queries to put them flat? -
django moldes create data duplicate
1.Models's name is UserRecord. 2.Bleow is the code of my view. @login_required def data(request, page, keyword,strEncode): current_username = request.user.username data_s = dosomething() #It takes a long time!!! UserRecord.objects.get_or_create(user=User.objects.get(username=current_username),MyRecords=keyword) # in order to create unique value return JsonResponse(data_s, safe=False) Request below url several times with no interval,something like threading concurrent. http://127.0.0.1:8000/data/1/test/english/ After this operation done,MyRecords column exists duplicate values. I found something in django document use 'with transaction.atomic' to deal with this problem,but did not work. -
where to save the verification code sent to the user for signing up
I'm somehow new to Django and it's my first time to implementing a signUp form with sms verification. I get the user mobile number and generate a random number and send to him; I want the generated code to be expired after 30 minutes and after that I don't need them, so it seems that it is not a good idea to save them in DB and after the expiration time, delete them. I wonder if anybody can help me with the the question that "what is the best way to implement this?" Thank you so much in advance -
NoReverseMatch in url in django app
I have url and everythis should be OK but I get an error. This is my url: url(r'^/(?P<genre>%s)$' % '|'.join([g.code for g in Genre.objects.all()]), EventListView.as_view(), name='genre'), Here is error message: Reverse for 'genre' with arguments '()' and keyword arguments '{u'genre': ''}' not found. 0 pattern(s) tried: [] In this line of html code: <a {% if genre == view.genre %} class="active" href="{% url 'events' %}" title="{% trans 'Reset Filter' %}"{% else %} href="{% url 'genre' genre=genre.code %}"{% endif %}>{{ genre.name }}</a> -
Django - annotating with filtered PREFETCH_RELATED
I have the following piece of code in my Django view: model_a_qs = ModelA.objects.some_complex_filter() result = ModelB.objects.prefetch_related(\ models.Prefetch('model_a', queryset = model_a_qs,\ to_attr = 'model_a_list')).\ values(....).\ annotate(SUM('model_a__salaries')) Now, the problem is that Django ignores filter when doing annotation. I know that Django offers conditional annotation tools, but in my case the filter is more complex that just some_field = some_value, and prefetch filter is what I need. Is it possible to make Django annotate by records that are only present in model_a_list? -
Django 1.10 - NoReverseMatch at /login/ when trying to render login page
This question has been asked for many times but I couldn't figure out my problem. I just started development with Django. I am developing a log app to authenticate users for a project with using Django in-built authentication system. I am facing an error when rendering login page through project.urls. url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}), I used LoginForm to customize html fields with bootstrap css classes. Here is the app views.py - @login_required(login_url="login/") def home(request): return render(request, "home.html") If a user is not logged in login_required redirect the user to login page. What I am getting the error when rendering login page in login.html file - <form method="post" action="{% url 'django.contrib.auth.views.login' %}"> When I remove login_required, home page works. Can anyone please elaborate the issue?