Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - DATE_FORMAT not work properly, i can't force Django to use a Date format
(First of all sorry for my bad English) I'm having a problem with the Date Formats, I'm from Argentina and here we use the Date Format dd/mm/yyyy. Well when I use a computer configured in spanish language the I see the dates and the date inputs perfect!for example in a detail view I see this in a date dd/mm/yyy but in any computer like my own one I see this mm/dd/yyyy And this generate a problem with my forms, in an especific case on my app when I go to save in the database a date input 03/01/2017 (Jan. 3. 2017) saves March 1 2017 ...... This is the configuration on the settings file USE_L10N = False DATE_FORMAT = 'd/m/Y' DATE_INPUT_FORMATS = ('d/m/Y') USE_TZ = True I use only DATE_FORMAT too, TZ False... I really don't know if is any way to force Django to use the format dd/mm/yyyy for all the cases. -
Django AllAuth - Google - choose username
We are using Django-allauth to allow users to signup and login using Google. The problem is that it automatically chooses first name from Google account as a username. Is it possible to make users to fill the username manually? I didn't find such settings in Allauth-google docs. These are ACCOUNT_ settings from settings.py ACCOUNT_AUTHENTICATION_METHOD = "username_email" ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_EMAIL_SUBJECT_PREFIX = EMAIL_SUBJECT_PREFIX ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN = 1 ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True ACCOUNT_PRESERVE_USERNAME_CASING = False ACCOUNT_USERNAME_MIN_LENGTH = 4 ACCOUNT_USERNAME_REQUIRED = True There is no such setting starting SOCIALACCOUNT_ in Docs. -
Django dynamic responsive forms
I have been learning django and wanted to create dynamic forms.So far, I have only created a dropdown menu. I wanted to create additional form fields for user input once a choice is made. I'm using ModelForm for the creation of dropdown menu as menu items will be decided during the runtime. My dropdown menu My views.py file from django.shortcuts import render,redirect from django.http import HttpResponse from .forms import ChoiceForm def hello(request): if request.method == 'POST': print 'in post' form = ChoiceForm(request.POST) if form.is_valid(): return HttpResponse(str(form.cleaned_data)) else: return HttpResponse('Invalid data') else: form = ChoiceForm() return render(request, 'choices.html', {'form': form}) My Models.py file from django.db import models from google.cloud import storage # Create your models here. class QueryInfo(models.Model): client = storage.Client() bucket_list = client.list_buckets() #Choice fields for user to select #choices must be in a iterable of length 2 BUCKET_CHOICES = ( (str(bucket_name.name), str(bucket_name.name)) for bucket_name in bucket_list ) selected_bucket = models.CharField(max_length=256,choices=BUCKET_CHOICES) My form file: from django import forms from gui.models import QueryInfo class ChoiceForm(forms.ModelForm): class Meta: model = QueryInfo fields = ['selected_bucket'] -
raw SQL in django views show error
For some special reasons we had to perform raw query in view.py file. (There is some page that user types an SQL query and sends it so our system and we should perform it and show the result of tat query) def query(request): result = None if request.method == "POST": form = forms.QueryForm(request.POST) if form.is_valid(): query_text = form.cleaned_data['query'] with connection.cursor() as cursor: try: cursor.execute(query_text) result = cursor.fetchall() except: result = cursor.statusmessage else: form = forms.QueryForm() return render(request, "portal/query.html", { 'form': form, 'result': result }) if we run something like SELECT * FROM table1, the try part would successfully run and if some queries that do not return some rows like UPDATE, the except part works. My question is that if we perform some meaningless queries like sakufhskghks, we want to see the error from DB, or any type of error from DB. Is that possible? tnx -
JSON formatting to a list in python
In python I get "n" number of json objects on request to an api. I need to convert this to a list and display it in django. What is the easiest way to do it. I did use json.dumps(data) it just dumps the entire data. -
AUTH_USER_MODEL refers to model 'accounts.User' that has not been installed
I'm using a custom user model, extended with AbstractUser. Here's my models.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.forms import UserCreationForm from django import forms # Create your models here. class User(AbstractUser): pass 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.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) enter code here So when I try to run the development server, or migrate the database, it returns this error: Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/shivbhatia/Desktop/WishList/accounts/models.py", line 6, in <module> from django.contrib.auth.forms import UserCreationForm File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 22, in <module> UserModel = get_user_model() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 198, in get_user_model "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.User' that … -
Connect 3 models in Django to access other model data
I have 3 models and in the 3rd model called Bookauth contains Foreign key for other two models Books, Authors. I want to get all the fields from 'Books' of a particular author(considering he wrote more then one book). I used manager in models but failed. Models class Authors(models.Model): aid = models.AutoField(primary_key=True) aname = models.CharField(max_length=200, blank=True, null=True) adescription = models.TextField( blank=True, null=True) def __str__(self): return self.aname class Books(models.Model): bid = models.BigIntegerField(primary_key=True) bname = models.CharField(max_length=200, blank=True, null=True) bdescription = models.TextField(blank=True, null=True) def __str__(self): return self.bname class Bookauth(models.Model): bid = models.ForeignKey(Books, on_delete=models.DO_NOTHING, db_column='bid', blank=True, null=True) aid = models.ForeignKey(Authors, on_delete=models.DO_NOTHING, db_column='aid', blank=True, null=True) Views Don't think this is relevent def getObject(request): all_books = Books.objects.all() html = serializers.serialize('json', all_books) return HttpResponse(html) #data = serializers.serialize("json", Books.objects.all()) #return HttpResponse(data, mimetype='application/json') def getAuth(request): all_auth = Authors.objects.all() htm = serializers.serialize('json', all_auth) return HttpResponse(htm) def bookAuth(request): all_keys = Bookauth.objects.all() key_serial = serializers.serialize('json', all_keys) return HttpResponse(key_serial) def book_search(request): b = request.GET.get('book', '') book = Books.objects.filter(pk = b) return HttpResponse(book) def author_search(request): x = request.GET.get('author', '') auth = Authors.objects.filter(pk= x) return HttpResponse(auth) Any suggestions on what I can do? -
How to pass Django server variable into React jsx?
I have a Django view that passes a model queryset and a string variable (order) class RestaurantListView(generic.ListView): model = Restaurant context_object_name = 'restaurants' template_name = 'routeyourfood/restodetails.html' paginate_by = 4 @method_decorator(require_GET) def dispatch(self, request, *args, **kwargs): return super(RestaurantListView, self).dispatch(request, *args, **kwargs) def get_queryset(self, **kwargs): self.pids = self.request.session['place_ids'] self.order = self.kwargs['order'] self.ordering_dict = { 'rating-asc': 'rating', 'rating-desc': '-rating', 'name-asc': 'name', 'name-desc': '-name', 'distance-asc': 'distance_from_route', 'distance-desc': '-distance_from_route' } if self.order == 'default': return Restaurant.objects.filter(place_id__in=self.pids) return Restaurant.objects.filter(place_id__in=self.pids).order_by(self.ordering_dict[self.order]) def get_context_data(self, **kwargs): context = super(RestaurantListView, self).get_context_data(**kwargs) context['order'] = self.kwargs['order'] return context I am trying to implement ReactJS into my front end. Currently, my template, restodetails.html has only a few CSS tags and no JS tag. I construct the entire page using just the template variables I have passed. But I can't see how I can integrate React into this. One way I got was to put React into a <script> tag in the head section, like here. But I'm keeping my React code in separate JSX files in the Django static folder, which I'm bundling using Webpack. I also don't like the idea of putting JavaScript into the template. Is there a way to pass those context variables into the JSX files? -
Celery Periodic Task not working on given crontab params
I need to perform some background tasks in Django at a particular time so I'm using @periodic_task in my tasks.py file. Basically I have two tasks: @periodic_task(run_every=(crontab(day_of_month='3-11', hour=11, minute=32)), name="invoice_simulation", ignore_result=False) def invoice_simulation(): print('---- task started-----') # Do something @periodic_task(run_every=(crontab(minute='*')), name="print_time_worker", ignore_result=False) def print_time(): print('Current time is: ', datetime.now()) On my local, everything is running properly but when I push my code to the server then only print_time() works and invoice_simulation is not working on the server. My code is deployed on Heroku after deployment celery logs on server look like... 2018-01-03T11:30:06.648963+00:00 app[worker.1]: 2018-01-03T11:30:06.648975+00:00 app[worker.1]: -------------- celery@73b10f01-6293-42ad-a0f5-867e4b39f43d v3.1.18 (Cipater) 2018-01-03T11:30:06.648976+00:00 app[worker.1]: ---- **** ----- 2018-01-03T11:30:06.648977+00:00 app[worker.1]: --- * *** * -- Linux-3.13.0-133-generic-x86_64-with-debian-jessie-sid 2018-01-03T11:30:06.648977+00:00 app[worker.1]: -- * - **** --- 2018-01-03T11:30:06.648978+00:00 app[worker.1]: - ** ---------- [config] 2018-01-03T11:30:06.648979+00:00 app[worker.1]: - ** ---------- .> app: __main__:0x7f8608f52358 2018-01-03T11:30:06.648980+00:00 app[worker.1]: - ** ---------- .> transport: redis://h:**@ec2-****.compute-1.amazonaws.com:17709// 2018-01-03T11:30:06.648981+00:00 app[worker.1]: - ** ---------- .> results: redis://h:*@ec2-****.compute-1.amazonaws.com:17709 2018-01-03T11:30:06.648981+00:00 app[worker.1]: - *** --- * --- .> concurrency: 8 (prefork) 2018-01-03T11:30:06.648982+00:00 app[worker.1]: -- ******* ---- 2018-01-03T11:30:06.648983+00:00 app[worker.1]: --- ***** ----- [queues] 2018-01-03T11:30:06.648983+00:00 app[worker.1]: -------------- .> celery exchange=celery(direct) key=celery 2018-01-03T11:30:06.648984+00:00 app[worker.1]: 2018-01-03T11:30:06.648984+00:00 app[worker.1]: 2018-01-03T11:30:06.648985+00:00 app[worker.1]: [tasks] 2018-01-03T11:30:06.648986+00:00 app[worker.1]: . djcelery_email_send_multiple 2018-01-03T11:30:06.648986+00:00 app[worker.1]: . invoice_simulation 2018-01-03T11:30:06.648987+00:00 app[worker.1]: . mdn_core_engine.celery.debug_task 2018-01-03T11:30:06.648987+00:00 app[worker.1]: . … -
Django Rest Framework drop fields based on request url
I have a ModelViewSet that exposes a contacts relation which is an extensive list of emails. class EmailSerializer(serializers.ModelSerializer): contacts = EmailContactSerializer(many=True, read_only=True) class Meta: model = Email fields = ('id','contact_count', 'contacts') class EmaiViewSet(viewsets.ModelViewSet): serializer_class = EmailSerializer If I visit the url api/emails I get a nice list of Emails with all it's contacts. My problem is that visiting this url is slow because of all the contacts it needs to retrieve for every Email instance. Now I want this detailed contact list to be available when requesting api/emails/<email_id>. What can I do in DRF to drop the contacts field when listing Emails ? -
How can I pass a python variable from html file to an external js file?
I am seperating my js in my html file to an external js file. In that case how can I pass my uid which is obtaining on session? I have ajax requests and i move all this to external js file? My external js (su.js) file now is submitBox = new Vue({ el: "#submitBox", data: { name: '', authType: 'authType', email: 'email', }, methods: { handelSubmit: function(e) { var vm = this; data = {}; data['name'] = this.name; data['email'] = this.nemail; data['auth-token'] = this.authType; $.ajax({ url: 'http://127.0.0.1:8000/alpha/add/post/', data: data, type: "POST", dataType: 'json', success: function(e) { if (e.status) { alert("Success") vm.pid=e.pid; } else { alert("Registration Failed") } } }); return false; }, }) In my html file (submit.html) i store the values of authType as <script> var authType = '{{uid}}'; </script> my views.py is @csrf_exempt def submit(request): if('is_logged_in' in request.session): id = request.session['authToken']; return render(request,"submit.html",{'uid':id}); else: return render(request,"submit.html",{}); So, how can I pass the value of authType to external js (su.js) file. It is using vue.js. Can anybody please help to obtain the result for me? -
How to update permission in Groups from Django without using admin
I would like to add/remove permissions to a particular group without the help of admin. I know how to update it with the help of admin, but I would like to change the permission programatically. django-admin -
Django REST - input of some form fields occure twice on the backend
Does anybody had the same problem? Some users' inputs are sent to the backend twice. Data are stored in JSON's object. Key-value schema doesn't trigger the problem. What users action can trigger this kind of problem? It doesn't happen every time, but only for some of the users. -
Django not print a user perms [on hold]
from django.contrib.auth.models import Permission permissions = Permission.objects.filter(user=request.user) for property, value in vars(permissions).iteritems(): print property, ": ", value and i get the following result How could i get the result from the above query ? -
Running Django management command on gae
Good day. How do I run py manage.py migrate On my Google app engine instance And how to run Django admin site after deploying. I've checked the tutorials online and most are not very clear -
Unit Testing a Django Form with a ImageField without external file
djang version: 1.11, python version: 3.6.3 I found this stackoverflow question: Unit Testing a Django Form with a FileField and i like how there isn't an actual image/external file used for the unittest, however i tried this approaches: from django.test import TestCase from io import BytesIO from PIL import Image from my_app.forms import MyForm from django.core.files.uploadedfile import InMemoryUploadedFile class MyModelTest(TestCase): def test_valid_form_data(self): im_io = BytesIO() # BytesIO has to be used, StrinIO isn't working im = Image.new(mode='RGB', size=(200, 200)) im.save(im_io, 'JPEG') form_data = { 'some_field': 'some_data' } image_data = { InMemoryUploadedFile(im_io, None, 'random.jpg', 'image/jpeg', len(im_io.getvalue()), None) } form = MyForm(data=form_data, files=image_data) self.assertTrue(form.is_valid()) however, this always results in the following error message: Traceback (most recent call last): File "/home/my_user/projects/my_app/products/tests/test_forms.py", line 44, in test_valid_form_data self.assertTrue(form.is_valid()) File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 183, in is_valid return self.is_bound and not self.errors File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 175, in errors self.full_clean() File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 384, in full_clean self._clean_fields() File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 396, in _clean_fields value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/widgets.py", line 423, in value_from_datadict upload = super(ClearableFileInput, self).value_from_datadict(data, files, name) File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/widgets.py", line 367, in value_from_datadict return files.get(name) AttributeError: 'set' object has no attribute 'get' why? I understand that .get() is a dictionary method, but i fail to see … -
It's slow to send email by the default EmailBackend of django 1.11 using Microsoft business email account
I'm using the default EmailBackend of Django 1.11, I just simply called the send_mail method as the ref. document said, here are my settings of the SMTP server: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'oalite@xxx.com' EMAIL_HOST_PASSWORD = 'xxxxx' EMAIL_SUBJECT_PREFIX = '[Irixi OALite Admin]' Here is my log outputted by smtplib.py: reply: b'250-CHUNKING\r\n' reply: b'250 SMTPUTF8\r\n' reply: retcode (250); Msg: b'SG2PR06CA0180.outlook.office365.com Hello [85.203.47.85]\nSIZE 157286400\nPIPELINING\nDSN\nENHANCEDSTATUSCODES\nAUTH LOGIN XOAUTH2\n8BITMIME\nBINARYMIME\nCHUNKING\nSMTPUTF8' send: 'AUTH LOGIN b2FBaXRl0GlyaXhpLmNvb0==\r\n' reply: b'334 UGFzc3dvcmQ6\r\n' reply: retcode (334); Msg: b'UGFzc3dvcmQ6' send: 'QEdBbH1w0DJuSwY=\r\n >>>>>>>>>>>>>>>>>> halted here for about 15s to wait the reply <<<<<<<<<<<<<<<<<<< reply: b'235 2.7.0 Authentication successful target host BLUPR04MB420.namprd04.prod.outlook.com\r\n' reply: retcode (235); Msg: b'2.7.0 Authentication successful target host BLUPR04MB420.namprd04.prod.outlook.com' send: 'mail FROM:<oalite@xxx.com> size=943\r\n' reply: b'250 2.1.0 Sender OK\r\n' reply: retcode (250); Msg: b'2.1.0 Sender OK' send: 'rcpt TO:<user.foo@xxx.com>\r\n' reply: b'250 2.1.5 Recipient OK\r\n' Please note that I was using the business email account of Microsoft, the domain xxx.com actually is our company domain name. Thanks for your help! -
Refresh div content after ajax request jQuery (JUST SIMPLY REFRESH LIKE F5)
Firstly, I know, I'll get many diss for this post, but whatev. I have searched everywhere, and everywhere is told about refreshing div by special content, nothing about simply refreshing. I've just send my form by POST in django (saving some data), and after that saving, I want refresh list within modal, but without refreshin whole page. Do I have to specify the whole path to modal etc. ? Is there jQuery command like F5 button but not to whole page, only a div? My code I'm working with: $(function(){ $('#js-submit-create-adres').on('click', function (e) { var form = $('#create-adres'); var _czy = ''; if ($('#id_czy_domyslny option:selected').text() == 'Tak') { _czy = 'True'; } else { _czy = 'False'; } $.ajax({ url: form.attr('data-url'), type: 'post', dataType: 'json', data: { ulica: $('#id_ulica').val(), kod_pocztowy: $('#id_kod_pocztowy').val(), miasto: $('#id_miasto').val(), kontrahent: $('#id_kontrahent').val(), czy_domyslny: _czy, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function(msg){ if(msg.result == 'done') { if(_czy == 'True'){ $('#kontrahent-adres').text(nowy_adres); } alert('saved'); $('#id_ulica').val(''); $('#id_kod_pocztowy').val(''); $('#id_miasto').val(''); // HERE I WANT TO RELOAD DIV NAMED '#name' } } }) }) }) -
email as username, case-sensitive email address
I use email address as a username in my Django application USERNAME_FIELD = 'email' but email field is case-sensitive so: test@example.com and TEST@EXAMPLE.COM are saved as two different users. It's normal or should I validate this somehow? -
How would you set up a django live project with git on a private server using gunicorn and nginx?
Is it possible to create a git project in a current live Django project and develop on it locally after a pull(or clone?) and push changes up again to have it automatically deploy? -
Django Translation vs Jquery
I'm developing multilingual website using django platform. Due to this, I have next question: What is better, to use django translations(translate using ugettext, locale and etc..) or using Jquery(add button with click function). I know, that I'll need to write both in django(msgid, msgstr(hand-written translation)) and in Jquery(hand-written json languages or depending on method). P.s I need 3+ languages. -
How to work around deprecated "include" in Django 2?
In particular, I am trying to find the equivalent solution for url(r'^accounts/', include('allauth.urls')), in Django 2. I have tried a number of different things, including custom views (which do work, but I have to create one for each purpose..unlike what I had to previously do). Is there an equivalent one liner in Django2? Thanks! -
why I don't get clean data when i use cleaned_data
I'm trying to create a login form for my site but when I use cleaned_data in my views.py I don't get the right data. here is my code: views.py def login_page(request): form = LoginForm(request.POST or None) context = { 'form': form } if form.is_valid(): print(form.cleaned_data) username = form.cleaned_form.get("username") password = form.cleaned_form.get("password") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect("/") else: print("Error") return render(request, "auth/login.html", context) forms.py class LoginForm(forms.Form): username = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control", "placeholder": "Username" } ) ) password = forms.CharField( widget=forms.PasswordInput( attrs={ "class": "form-control", "placeholder": "Password" } ) ) login.html <form action="POST">{% csrf_token %} {{ form }} <button type="submit" class="btn btn-default">Submit</button> </form> and here is what I get when I fill username and password field and click on submit. print(form.cleaned_data) shows there is data in url fields that I want to use but I can't access them. console -
@detail_route: object has no attribute - Django Rest Framework
I get an issue about @detail_route. Hope your guys helps! This is my viewsets. I use decorators to import detail_route My viewsets: class PhotoUpdateSerializer(ModelSerializer): class Meta: model = Photo fields = [ 'image', 'is_public', 'caption' ] class UploadAvatarPhotoAPIView(ReadOnlyModelViewSet): serializer_class = PhotoUpdateSerializer queryset = Photo.objects.all() @detail_route(methods=['POST']) def upload_avatar(self, request, username): avatarqs = Photo.objects.create( user=self.request.user, caption=self.caption, image=self.image, is_public=self.is_public ) serializer = PhotoUpdateSerializer(avatarqs) return Response(serializer.data) Error: 'UploadAvatarPhotoAPIView' object has no attribute 'caption' I think 3 lines are error: caption=self.caption, image=self.image, is_public=self.is_public -
Django cannot delete cookie and session after logout, cahing on nginx level, auth system not work?
nginx cahing everything, if I login to the system, then I can no longer exit it until the caching expires, since I'm Logout from the account, i need to know how to delete cookies and session, DJANGO !?