Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Password validation/matching not working in django
I have used the following two methods on login page but django is letting users to register themselves with different passwords and is not showing the ValidationError. from django import forms from django.contrib.auth import ( authenticate, get_user_model, ) User = get_user_model() class UserRegistrationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm Password') password2 = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'email', 'username', 'password', 'password2', ] method no.1: def clean(self): cleaned_data = super(UserRegistrationForm, self).clean() password = cleaned_data.get('password') password2 = cleaned_data.get('password_confirm ') if password and password2: if password != password2: raise forms.ValidationError("The two password fields must match.") return cleaned_data method no.2: def clean_password(self): password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') if password and password2 != password2: raise forms.ValidationError('Passwords must match') return self.cleaned_data FYI using django 1.10 and python 3.4 -
New to Django - How do i serialize raw queryset in django
I am relatively new to Django framework and working on getting my first application running. I am encountering the below issue when i try to pass my queryset from my view to the template. My view.py: with connection.cursor() as cursor: cursor.execute("SELECT TOP(5) * FROM xxx WHERE sbu = %s", [sbu]) def dictfetchall(cursor): columns = [col[0] for col in cursor.description] return [dict(zip(columns,row)) for row in cursor.fetchall()] results = dictfetchall(cursor) class DecimalEncoder(json.JSONEncoder): def _iterencode(self, o, markers=None): if isinstance(o, decimal.Decimal): return (str(o) for o in [o]) return super(DecimalEncoder, self)._iterencode(o, markers) json_result = json.dumps(data, cls=DecimalEncoder) I end up with the below error: Decimal('28.80') is not JSON serializable Any suggestions? Am i missing a step somwhere? I have lot of decimal values in the queryset. -
converting long format time into proper time in django templtes list?
I have a time value for every entry coming in long time format from API.So i want to convert it into human readable form. my API values are:- "data": [ { "id": 33613, "virtualNewsId": 30513, "newsCommentText": "@39586!~~!Abhay_raj_singh_chauhan!~~!Abhay%20Raj%20%20!>>! @39586!~~!Abhay_raj_singh_chauhan!~~!Abhay%20Raj%20%20!>>!", "user": { "id": 39561, "name": "chatuser", "username": "chatuser", "email": "chatuser@mail.com", "profileImage": "", "profileImageThumbnail": "", "isfollow": false }, "image": null, "createdAt": 1493978312000 } now how can i convert createdAt human readable forn in django template.I have many values like this and uaing forloop to display on tables.So how can i achieve this. -
Django Group by query?
I am using django ORM for fetching data using group by query. The raw postgresql query is- select date_trunc('day', time) as Time ,count(status) from table where group_id='2177' and status=1 group by date_trunc('day', time) order by time desc limit 7 offset 0; and it is returning the correct output.. time | count ---------------------------+------- 2017-05-04 00:00:00+05:30 | 12 2017-05-03 00:00:00+05:30 | 26 2017-05-02 00:00:00+05:30 | 25 2017-05-01 00:00:00+05:30 | 26 2017-04-30 00:00:00+05:30 | 26 2017-04-29 00:00:00+05:30 | 26 2017-04-28 00:00:00+05:30 | 26 (7 rows) I am using django annotate function to acheive this - here is the django query - records = TableModel.objects.filter( group_id=group_id, status=1, time__range = get_time_range(range) ).annotate( period=DateTrunc('day', 'time') , count=Count('status') ).annotate( period = DateTrunc('day', 'time') ).order_by('-time') On Debug, I found out that django is internally converting it to - SELECT "table"."id", "table"."time", "table"."status", "table"."group_id", DATE_TRUNC('day', "table"."time") AS "period", COUNT("table"."status") AS "count" FROM "table" WHERE ("table"."group_id" = '2177' AND "table"."status" = 1 AND "table"."time" BETWEEN '2017-04-28 11:47:21.421755+00:00' AND '2017-05-05 11:47:21.421755+00:00') GROUP BY "table"."id", DATE_TRUNC('day', "table"."time") ORDER BY "table"."time" DESC; here is its o/p (it contains more number of rows)- id | time | status | group_id | period | count --------+---------------------------+----------------------+------------+---------------------------+------- 267821 | 2017-05-04 10:36:13+05:30 | 1 | 2177 | … -
In django middleware class I am getting TypeError: __init__() takes exactly 2 arguments (1 given) where __init__ is __init__(self,get_response)
I am getting the following error: File "/usr/local/lib/python2.7/dist-packages/django/contrib/staticfiles/handlers.py", line 63, in call return self.application(environ, start_response) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 170, in call self.load_middleware() File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 52, in load_middleware mw_instance = mw_class() TypeError: init() takes exactly 2 arguments (1 given) -
Django/Javascript - Data won't display in chart
Chart shows correctly like so: But this one does not display the bar: This line is displayed as warning/error where default2 is: Unresolved variable default2 I have commented down below for you to see and added a picture where this error displays: How do I make the chart above appear with a bar like the other one? Been doing these for days and hours and looked for answers here with no luck. Hopefully you can see where I went wrong. Still a newbie so I appreciate all your help, folks! chart.js var endpoint = '/api/chart/data/'; var defaultData = []; var labels = []; var defaultData2 = []; var labels2 = []; $.ajax({ method: "GET", url: endpoint, success: function (data) { labels = data.labels; defaultData = data.default; setChart() }, error: function (error_data) { console.log("error"); console.log(error_data) } }); $.ajax({ method: "GET", url: endpoint, success: function (data) { labels2 = data.labels2; defaultData2 = data.default2; # default2 displays as incorrect/warning??? setChart2() }, error: function (error_data) { console.log("error"); console.log(error_data) } }); function setChart2(){ var ctx = document.getElementById("myChart5"); var myChart5 = new Chart(ctx, { type: 'bar', data: { labels2: labels2, datasets: [{ label: 'Total', data: defaultData2, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', … -
How to pass variable from view page to base template
I am trying to login the user into his profile and need to pass the username to a navbar in a base template. I have base.html(base template) and index-client.html(body template). Now from login view, i would like to pass username value to base.html. Code after user authentication is: if user is not None: if user.is_active: login(request, user) return redirect('index-client.html') I need to pass username to base.html i.e. a base template. -
How to social sign up with django-allauth with all data registred?
I have custom user in my models and I want to give the possibility to register via social media ( facebook and google + ) . The flow is : If the data recovered from social account fill all the user fields then the user is redirected to home page. Else (If the data recovered from the social media is not sufficient (for example the field birthday is empty) the user should be redirected to the signup form to complete the requested field and sign up without sending the confirmation email. Can anyone help me please ? Thanks ! -
IntegrityError when using .save() on OneToOneField in Django
I have 2 models class User(models.Model): email = models.CharField(max_length = 100) password = models.CharField(max_length = 100) class Authentication(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) token = models.CharField(max_length =50, null = True) Here is the code I use for login in views.py from user.models import User, Authentication import uuid from django.db.utils import IntegrityError user = User.objects.get(pk = request.user.id) token = uuid.uuid4().hex try: Authentication.objects.create(user = user, token = token) except IntegrityError: user.authentication.token = token user.authentication.save() return JsonResponse({'token':token}) The problem I meet here is everytime a user login, I will generate a new token and save in the database. The error appears at the line user.authentication.save() The error is: django.db.utils.IntegrityError: (1062, "Duplicate entry '30' for key 'user_id' ") The 30 is the user_id existed in Authentication models when login in the second time ( the first time login is always succeed). I solved this problem by using these codes: except IntegrityError: au = Authentication.objects.get(user = user) au.token = token au.save() But I dont know why i got this bug. I used to do the first approach many times but not got no bugs at all. Anyone has faced to this problem can show me the way to solve this? Thank you -
how to use RemovedInNextVersionWarning?
I've written a library Django, I want to update it. But I need that to the people who use it say that this function will be removed in the future, how should I say this? class ModelAdmin(admin.ModelAdmin): def __init__(self, *args, **kwargs): super(ModelAdmin, self).__init__(*args, **kwargs) self.formfield_overrides = overrides warnings.filterwarnings( 'ignore', 'please use "ModelAdminJalaliMixin". example: class YourClass (admin.ModelAdmin, ModelAdminJalaliMixin):', RemovedInNextVersionWarning ) -
Translating plural name
So i am not really sure is this problem of Django generating translation or Poedit problem. In class meta i have verbose_name and verbose_name_plural for example lets say "Store" and "Stores". When i generate it does not show the plural one to translate. #: testapp/models.py:344 #, fuzzy #| msgid "Store" msgid "Store" msgstr "Translated String" I have a feeling that its automatically connecting to non plural word and it does not let me translate the plural one. Any idea is this poedit thing which is wrong or django is generating it that way? -
Django - deployed, 403 for static but it should have permission, wsgi + Apache
my deployed Django project can't access the static files, I get 403 for all of them when inspecting in Chrome. I added the following to my 000-default.conf where I also have the WSGIScriptAlias etc.: Alias /static/ /home/budget/static/deploy/ <Directory /home/budget/static/deploy> Required all granted </Directory/ The static files exist in the budget/static/deploy folder. Should this not give the required permissions? What do I have to change to get rid of the 403? It is running on Ubuntu 16.04. Edit: settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = ( #os.path.join(BASE_DIR, 'budget/static'), os.path.join(BASE_DIR, "static"), ) STATIC_ROOT = os.path.join(BASE_DIR, "static/deploy/") -
What's the most pythonic way to get name of the field when an exception related to IntegrityError is thrown?
I'm developing an API with DRF and I want to generate and return proper custom error messages when an exception related to IntegrityError is thrown. To do this, I've implemented a custom exception handler. Inside the custom exception handler, I want to get the name of the field that causes the error from the Exception instance and then I'll generate and return proper message in the response. Currently, I can do this by parsing the message attribute of the Exception instance but I'm not sure this is the best possible solution. So, is there any pythonic way to get the name of the field from the Exception instance when an exception related to IntegrityError is thrown? Thanks! -
Downloading Excel files with Django and Angular2
I have a project in which I save files in SMB folder and use Django for the backside and Angular 2 for the front side. I have successfully managed to download the .csv files, but when the .xls file is downloaded, it is corrupted. The lines in the file look like this: Admin-Grisham B�a�=���=o'��x<�*8X@�"��1���Arial1���Arial1���Arial1���Arial1�?�Arial1��Arial1�$�Arial1���Arial1���Calibri1� This is my views.py file: '''Download file''' def get(self, request, file_name): bicloudreposervice = BiCloudRepoService() file_obj = bicloudreposervice.get_user_file(request.user.email, file_name) file_path = file_obj.name with open(file_path, 'rb') as tmp: if 'xls' in file_name: resp = HttpResponse(tmp, content_type='application/vnd.ms-excel;charset=UTF-8') else: resp = HttpResponse(tmp, content_type='application/text;charset=UTF-8') resp['Content-Disposition'] = "attachment; filename=%s" % file_name self.logger.debug('Downloading file') return resp The relevant function in the service file in typescript looks like this: downloadFile(fileName: string){ let headers = this.headers; let options = new RequestOptions({ headers: headers }); return this.http.get(this.connectorsUrl+'download-file/' + fileName + '/', options) .map(res => res) .catch(this.utils.handleError); } And the component file: import * as FileSaver from "file-saver"; ... downloadFile(name){ this.connectorsService.downloadFile(name).subscribe( res => {this.successDownloadFile(res, name);}, error => this.errorMessage = <any>error, ()=> {}); } successDownloadFile(res: any, name: String){ this.showLoader = false; let blob; blob = new Blob([res._body], {type: 'application/vnd.ms-excel'}); FileSaver.saveAs(blob, name.toString()); } The corresponding html file: ... <div (click)="downloadFile(file.name)"> <i class="material-icons">file_download</i> </div> ... I use the external library … -
What does it mean by using 'source <some env path>' command in linux?
After creating virtual environment virtualenv env why do we need to fire 'source' command ? source env/bin/activate ) What is the use of source command in general in linux ? -
Python(Django) giving error while pushing on heroku
I am new to heroku as well as python (Django). i have made an app in django and want to push on heroku. but on git push heroku master it giving me this error. Writing objects: 100% (245/245), 10.37 MiB | 110.00 KiB/s, done. Total 245 (delta 35), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing Python-2.7.13 remote: -----> Installing pip remote: -----> Installing requirements with pip remote: /app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda all: line 5: /app/.heroku/python/bin/pip: No such file or directory remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy.... remote: remote: ! Push rejected to djangoshopnror. remote: To https://git.heroku.com/djangoshopnror.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/djangoshopnror.git' i have requirements.txt file and runtime.txt file. runtime.txt look like this Python-2.7.13 and requirements.txt look like this BestBuyAPI==0.0.51 dj-database-url==0.4.2 Django==1.9 django-cors-headers==2.0.2 djangorestframework==3.6.2 djangorestframework-jwt==1.10.0 ebaysdk==2.1.4 gunicorn==19.7.1 lxml==3.7.3 psycopg2==2.7.1 PyJWT==1.5.0 pytz==2017.2 requests==2.7.0 virtualenv==15.1.0 wapy==1.0.0 whitenoise==3.3.0 one weired thing is when i change runtime.txt with python version 3.5.x it works. but due to some reasons i have to use python 2.7.x . can anyone have answer about this. … -
Issues with functions Django
Hello I have a code that I am trying to understand. I am new to Django :( def custom_forecast(request, pk=None): if pk is not None: param = get_object_or_404(Parameters.objects.filter(Q(user=request.user) | Q(system_parameter=True)), pk=pk) #iza l model form = ForecastForm(request.POST or None, instance=param) else: form = ForecastForm(request.POST or None) if request.method == 'POST': if form.is_valid(): if 'save' in request.POST:#kerml sayev obj = form.save(commit=False) obj.user = request.user obj.type = "custom_forecast" obj.save() messages.info(request, 'Saved!') return redirect(obj.get_forecast_url()) else: obj = ForecastQueue.create(request.user, 'custom_forecast', json.dumps(request.POST) obj.save() return redirect(obj.get_url()) else: data = { 'active_page': 'custom_forecast', 'form': form, 'display_result': False } else: data = { 'active_page': 'custom_forecast', 'form': form, 'display_result': False } data['system_params'] = Parameters.objects.filter(system_parameter=True).all() return render(request, 'custom_forecast.html', data) Basing on my basic knowledge it is a method to display a forecast form if the parameters are not in the database (pk=none) The first else: else: obj = ForecastQueue.create(request.user, 'custom_forecast', json.dumps(request.POST) obj.save() Is to create user before choosing parameters ? -
How to make Django support IETF language tag (xx-YY format)?
We have a Django site that supports many languages. Trying to add opensearch plug-ins support for multi-language. OpenSearch.org spec uses IETF language tag (xx-YY format). Default Django setup uses exact matching. The current state, the site support only xx form anything else return E404. Example: http://website.domain/en/... Depending on user configuration the browser insert language parameter as xx or xx-YY. It needs to work for both If xx-YY is not available, site should provide xx (mother country language) results. if xx is not available, site should provide en (English) results. Example of URL to be supported: http://website.domain/fr-YY/... fall-back to: http://website.domain/fr/... http://website.domain/xx/... fall-back to: http://website.domain/en/... Example URL from Mozilla site: https://support.mozilla.org/en-US/questions/949545 How to make Django support IETF language tag (xx-YY format)? I'm looking even for hints to implement this without modifying the django upstream code. -
Django: querying for entries immediately before and after another
I am trying to perform a query using a time field. Let's say we have a school timetable: ENGLISH -- MATH -- SCIENCE -- HISTORY -- ART -- GYM Each of these lessons have an attached timeslot, comprised of a starting time and a ending time. There may be gaps (i.e. morning break, lunch break, afternoon classes...) We want to know what classes are immediately before and after SCIENCE, these would be MATH and HISTORY. What I tried is building two queries: one for the classes than come before SCIENCE and another for those that come after. Then I order them by start time in reverse order and normal order respectively, and get the first result, which would be what I am after. Here it is: previous_class = classes.filter(end__lte=science.start).order_by('-start')[0] next_class = classes.filter(start__gte=science.end).order_by('start')[0] However, this looks like a costly operation since it needs to make two queries, and then query for all classes coming before or after, only to get one of them. I can't just do the following: classes.filter(Q(end__lte=science.start) | Q(start__gte=science.end)) Because this is going to match all classes before and after SCIENCE, not just the immediate ones. I wonder if there is any way I could build just one … -
how to create the dynamic web chart by drag-n-drop fields
I am new to developing the responsive web page. I saw the website(www.vizydrop.com) to provide one powerful functions which can visualize the data by drag-n-drop its fields - please the attached image for this function. So I am very keen to know how that can be done and would like to make a try. I suppose there would be plenty of ways to do so, but since I am more interested on javascript and Python, if somebody can let me know the way done by both of those, or share some sample codes, it would be highly appreciated. Best regards Patrick -
django, How to use bulk_create(objs,batch_size=None)
In bulk_create(), what does batch_size means? I tried two codes, Person.objects.bulk_create([ Person (name='Tom', age='24', job='student', hobby='football'), Person (name='Steve', age='33', job='doctor', hobby='movie'), Person (name='Mike', age='55', job='professor', hobby='tennis'), ]) and Person.objects.bulk_create([ Person (name='Tom', age='24', job='student', hobby='football'), Person (name='Steve', age='33', job='doctor', hobby='movie'), Person (name='Mike', age='55', job='professor', hobby='tennis'), ], batch_size=2) In second case I added 'batch_size' but that two codes didn't have differences. What 'batch_size' means? Hoe to use this batch_size? -
WKHTMLtoPDF load CSS and Media files
Im trying to use images stored in the MEDIA folder in the PDF Im using a code: <img src"{{MEDIA_URL}}{{booking.photo.path}}"> This loads a broken image in the generated PDF. Additionally the bootstrap which i am attempting to load from cdn also doenst work. Any help would be appreciated. -
Rounding up a number to nearest 1 in django template
I am having a hard time trying to do some simple math inside my django template with mathfilters, i divide the number by 12, and then multiply it with 1.18, for this i use the following formula: {{coffee.orderedQuantity|div:12000|mul:1.18}} Which works fine, but it returns a decimal number, which i would like to alway be rounded up, so if the decimal is 1.2342 it should show as 2 in my template. Any help or suggestions would be appreciated :) -
Set created by modified by dynamically with mixin
Coming from the rails world, I was pleased to find out about mixins: I set up a Basic mixin core/mixins.py from django.db import models from django.contrib.auth.models import User class Timestamps(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True And then my Event model in core/my_app/models.py from core import mixins as core_mixins class Event(core_mixins.Timestamps): # ... all jolly good, but what if I wanted to extend this a bit and create a more dynamic mixin? Advanced mixin core/mixins.py from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import pre_save from cw_core.requestprovider.signals import get_request class Trackable(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='created_XXX') # <-- ??? updated_by = models.ForeignKey(User, related_name='updated_XXX') # <-- ??? class Meta: abstract = True @receiver(pre_save, sender=Event) # <-- ??? def security_attributes(sender, instance, **kwargs): request = get_request() instance.updated_by = request.user if instance.id is None: instance.created_by = request.user core/my_app/models.py from core import mixins as core_mixins class Event(core_mixins.Trackable): # ... How would I dynamically set the related_name? I found this question but I have not found the variables I could use in strings, are there any docs? Also how would I dynamically set the sender in the @receiver call? My … -
How do I increase performance of Django Project with huge data?
I have 4 models, one is main model which will have only some info and remaining 4 models will have multiple data like images, reviews, contacts. Now, I need to pass/render complete data to templates like Main model data and remaining models data which have foreign key of main mode. I wrote some function to prepare the data in format, which includes every model data. This function will loop over the all results of Main model and then will get the sub models data and will arrange the data in dict format. Because of this function, it's taking huge time to prepare the data. Also I have map page like in google map page, with multiple markers and side multiple places to display. here also I am losing performance, because of multiple markers. So I thought to implement Lazy loading, Can any one suggest me, what I can do to increase the performance?