Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why would autocommit in django 1.4 slow down unit tests?
Django 1.4 operates by default with the database-level autocommit setting off. I have recently tried turning this setting on and it has slowed down my test suite considerably. DATABASES['default']['OPTIONS'].update({'autocommit': True}) My understanding is that now every call to create, save etc. by default opens a transaction and issues a commit statement. Would the cost of all these additional transactions be enough to explain the slow-down of the unit tests? How does the django TestCase transaction behaviour come in to play with this (operating each test within a transaction and rolling back once completed)? Should we expect the performance reduction in the unit tests to be reflective of performance of the views in production? -
Why does Microsoft SQL Server respond with malformed packets to Django web server?
I have a web based Django application that communicates with a Microsoft SQL Server Database that is setup on a different server. Recently, the users of the app have complained that the app is responding very slow (30s to 2m delay on every request), so I ran some Wireshark tests to see where the delay comes from. I noticed that the Django app sends the requests to the DB in less that 1 sec, so the problem seems unrelated to the app itself. On the other hand, the DB responds with malformed TDS packets and it takes about 30s until it successfully sends the response. Unfortunately, the app is installed on a customer's server that had very sensitive data, so I was not able to get any exports of the Wireshark logs. If it's any help, the Django app is hosted a Windows Server VM and the database is hosted on a physical server. What I need to know is what could cause the malformed packets from the SQL Server response. Thanks! -
How can I pass a parameter to a Bootstrap modal?
While developing a website, I've encountered this problem: I've a list of panels movies, created using a for loop, and each one of them has a "Delete" button. Each delete button has an unique id (movie id in my database). I need to send that id to the backend, developed in Django, using AJAX. How can I achieve this? Here is my HTML code for creating the movie panel list: <ul> {% if film_list %} {% for film in film_list %} <li class="list-group-item"> <div class="row"> <div class="col-md-3 col-xs-3 col-sm-3 col-xl-3 name"> <img width="50" height="50" src= {{ film.poster }} alt= {{ film.title }}> <strong> {{ film.title }} </strong> </div> <div class="col-md-9 col-xs-9 col-sm-9 col-xl-9"> <div class= "col-md-4 col-xs-4 col-sm-4 col-xl-4"> <button id = "{{ film.id }}" class="btn boton-delete" data-toggle="modal" data-target=".modal-delete"> <span class=" glyphicon glyphicon-trash delete"></span> Borrar película </button> </div> </div> </div> </li> {% endfor %} {% endif %} </ul> And here is the HTML code of the modal: <div class="modal fade modal-delete" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"> <div class="modal-dialog modal-md"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">¿Está seguro de que quiere borrar esta película?</h4> </div> <div class="modal-footer"> {% csrf_token %} <button type="submit" class="btn btn-success modal-btn-si">Si</button> <button type="submit" … -
Django database connection library issue
I faced an illogical issue. When I use connection created from cx_Oracle, It is working as assumed. But when I use Django DB connections, It is giving result but not as expected. import cx_Oracle from django.db import connections import pandas as pd dsn_tns = cx_Oracle.makedsn('10.253.1.201', '51621', 'DMSMTREC') cx_Oracle_conn = cx_Oracle.connect('MTRECDB', 'MTRECDB', dsn_tns) django_conn = connections["DB2"] # In django settings, I have a created "DB2" and passed the same parameters. query = ''' SELECT (T1.ACCEPTED- T2.CANCELLED) AS "NET" FROM ( SELECT ID, COUNT(1) AS ACCEPTED FROM ACCEPTED_TABLE GROUP BY ID ) T1 LEFT JOIN (SELECT ID, COUNT(1) AS CANCELLED FROM CANCELLED_TABLE GROUP BY ID) T2 ON T1.ID=T2.ID ''' df1 = pd.read_sql(query, cx_Oracle_conn) # Gives right result df2 = pd.read_sql(query, django_conn) # Gives only count of T1.ACCEPTED(T2.CANCELLED having 0 count) Questions: What is the reason for this? How a connection can effect the execution of query? Is it a bug of Django? Or Do I need to use django connections in other way? Versions: Django == 2.1.2 Python == 3.6.7 'ENGINE': 'django.db.backends.oracle' # As mentioned in django document in DB connections -
Django rest API formatting data
I am new in Django rest API. I create an API for my project where user can get data from the system via API. I serialize data and pass also but I also want to count the result and pass that value too. my view.py is here def categorySearch(request, slug): itemViewCategory = Item.objects.raw('''select *, company.slug as companySlug, company.name as companyName, field.id as fieldId, field.name as fieldName, category.name as categoryName from company inner join category on company.business_type = category.id inner join category_field on category_field.category_id = category.id inner join custom_field as field on category_field.field_id = field.id where category.id = (select id from category where slug= %s) and field.name LIKE %s order by company.name ''', [slug, product]) itemViewCategoryCount = Item.objects.raw( '''select *, COUNT(company.name) as companyCount from company inner join category on company.business_type = category.id where category.id = (select id from category where slug= %s) order by company.name ''', [slug]) results = [] for val in itemViewCategory: place_json = {} place_json['name'] = val.name place_json['email'] = val.email place_json['address'] = val.address results.append(place_json) return JsonResponse(results, safe=False) where its return data like this [ { "name": "Washing Plants", "email": "ababil.washing@yahoo.com", "address": "ababil.washing@yahoo.com" }, { "name": "Washing Plants", "email": "info@dekkoisho.com", "address": "Holding # 79/1, Chandra, Kaliakoir" }, { "name": … -
Sorting records by calculated field computed in the model
So I need to ve able to sort the records by a calculated field which is calculated in the model side . So my model is something like: class User(models.Model): data = models.DateTimeField(null=True, blank=False,) average = None # Average avg field has a value # when get_deviation is being added in list_display def get_deviation(self): return abs(self.average- self.data) get_deviation.short_description = 'deviation' get_deviation.allow_tags = True And in my admin Model: class UserAdmin(admin.ModelAdmin): list_display = ('data') def changelist_view(self, request, extra_context=None): # other code #average value is calculated and seted in user model list_display = ('data','get_deviation') return super(UserAdmin, self).changelist_view(request, extra_context) So I need to be able to sort by the new field in the record list . any advice? -
Django Logging all the GET requests
I'm trying to put all the GET requests that appear in console into the database from django. For example: console log: [23/May/2019 13:58:44] "GET /testapp/ HTTP/1.1" 200 409 [23/May/2019 13:58:45] "GET /testapp/page2/ HTTP/1.1" 200 172 I'm trying to get the timestamp, page URL and user name from it and put in the database, so the entries looks something like this in the database: id user pageURL timeStamp 96 naeem /testapp/ 2019-05-23 09:37:12.640613 97 naeem /testapp/page2/ 2019-05-23 09:37:13.317271 This is the code I have written for the middleware: from TestApp.models import ActivityLog class AccessLogs(object): # One-time config def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) # Add the user and page info into DB try: ActivityLog(user=request.user, pageURL=request.path).save() except Exception as e: print(e) return response The problem is that it gives me the desired result, but it does not get the results if I click on a downloadable file, or an image. Like I have a static image on the website which is downloaded on click, like: <a href="{% static 'TestApp/media/cat.jpg' %}" download>Click here to open image</a> So if I click on that, it shows in the console that the image was downloaded, but it doesn't put that … -
How to select data from a queryset and group by counts for a specific date
When I query my database I get the same entry three times with three different counts. In the result list I would like to get just one entry showing the sum of these counts. What I would like to display is the total for a specific period. In my query I enter the dates (from - until), a metric_type, a data_type and a year of publication. For instance I on the website when I enter from 201903 until 201905 I retrieve three titles that have been accessed in this period as well as how many times they have been accessed. Title, [...], Counts Title A 3 Title A 5 Title A 3 What I would need is something like Title, [...], Total for that period Title A 11 In views.py I have the following code: q_report = Q() var0 = self.request.GET.get("period1", "") var1 = self.request.GET.get("period2", "") var2 = self.request.GET.get("metric_type", "") var3 = self.request.GET.get("data_type", "") var4 = self.request.GET.get("YOP", "") if var0: q_report = q_report & (Q(month__gte=var0) & Q(month__lte=var1) ) #q_report_count = q_report_count & (Count(month__gte=var0) & Count(month__lte=var1) ) if var2: q_report = q_report & (Q(metric_type=var2)) #q_report_count = q_report_count & (Q(metric_type=var2)) if var3: q_report = q_report & (Q(data_type=var3)) if var4: q_report = q_report … -
Django-polymorphic - how to set ordering?
I use django-polymorphic for multiple product types. class Product(PolymorphicModel): order = models.PositiveSmallIntegerField(default=999, verbose_name='Poradie') class WoodProduct(Product): .... class IronProduct(Product): .... class PlasticProduct(Product): .... I want to set default ordering (or explicitly specify when filtering QuerySet) based on 1. model type 2. order attribute The closest I got is to set ordering = ['polymorphic_ctype_id'] in the class Meta of Product model. So now I have grouped products by model type but I can't set, which type will be the first,second etc... How can I ensure that Product.objects.all() will return QuerySet with ordering - WoodProducts , PlasticProducts, IronProducts ? -
permission in APIView desnt work and response. but should response access deny
in below code i want add some permission but it doesn't work exactly . when i change permission to "IsAdmin" that work correctly and response "access deny" when i want get TeacherPostStatistic.but i dont know why this permission that i need doesn't work?thank you. view.py: class TeacherPostStatistic(generics.RetrieveAPIView): permission_classes = (ClassCoTeacherPermission, ClassOwnerPermission) def get_klass(self): class_id = self.kwargs['class_id'] return Class.objects.get(id=class_id) def get(self, request, *arg, **kwargs): klass = self.get_klass() response = Post.post_count_last7days(klass) return JsonResponse(response, safe=False) urls.py: url(r'^teacher/(?P<class_id>[0-9]+)/post-statistic/$', views.TeacherPostStatistic.as_view()), models.py: class Post(models.Model): title = models.CharField( _("Post title"), max_length=100, blank=True, default="", ) description = models.CharField( _("Post description"), max_length=1500, blank=True, ) type = models.CharField( _("Post type"), max_length=1, choices=TYPE_CHOICES, ) create_date = models.DateTimeField(default=timezone.now) emoji_count = JSONField(default=get_empty_dic) like_count = models.IntegerField(default=0) writer = models.ForeignKey( User, related_name='written_posts', related_query_name='written_post', null=True, on_delete=models.SET_NULL ) klass = models.ForeignKey( 'klass.Class', related_name='posts', related_query_name='published_post', on_delete=models.CASCADE ) users = models.ManyToManyField( User, through='PostUserActivity', related_name="posts", blank=True, ) files = models.ManyToManyField(File) @classmethod def post_count_last7days(cls, klass): post_per_day_chart = {} for past_day in range(0, 7): count_post_in_past_day = cls.objects.filter(klass__exact=klass, create_date__date=date.today()-timedelta(days=past_day)).count() post_per_day_chart[past_day] = count_post_in_past_day print(post_per_day_chart) return post_per_day_chart permission.py: class ClassCoTeacherPermission(permissions.BasePermission): def has_object_permission(self, request, view, obj): return self.has_perm(user=request.user, klass=obj) @classmethod def has_perm(cls, user, klass): co_teacher = ClassCoTeacherMembership.objects.filter(klass=klass, co_teacher=user) if not co_teacher.exists(): raise exc.UserIsNotCoTeacherOfTheClass return True # TODO: using raise inside permission class should be revised class … -
How to display model fuction in Django template
What I am trying to do is to get the data from my model to show up a bootstrap modal. What I am doing right now is trying to pass the function data into the view and through the view I am trying to show the with in the modal. The issue I am encountering is: Invalid block tag on line 47: 'show_profile', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Am I doing something wrong when I am trying to pass the data in or is something wrong with my tag or something else? Model class mentee(models.Model): application_date_time = models.DateTimeField() # status = models.CharField(max_length=30) fname = models.CharField(max_length=30) full_name = models.CharField(max_length=30) lname = models.CharField(max_length=30) email = models.CharField(max_length=30) phone = models.CharField(max_length=30) bio = models.CharField(max_length=1700) gender = models.CharField(max_length=30) objectives = models.CharField(max_length=100) years_of_experience = models.CharField(max_length=20) university = models.CharField(max_length=30) graduation_year = models.IntegerField() major = models.CharField(max_length=30) class_standing = models.CharField(max_length=30) city = models.CharField(max_length=30) country = models.CharField(max_length=30) student_type = models.CharField(max_length=30) profile_pic = models.CharField(max_length=30) linkedin = models.CharField(max_length=30) GitHub = models.CharField(max_length=30) website = models.CharField(max_length=30) resume = models.CharField(max_length=100) area_of_concentration = models.CharField(max_length=30) roles_of_interest = models.CharField(max_length=100) meet_in_person = models.BooleanField() preferred_years_of_experience = models.CharField(max_length=20) organization_of_interest = models.CharField(max_length=30) area_of_expertise = models.CharField(max_length=100) skills_desired = ArrayField(ArrayField(models.CharField(max_length=100))) gender_preference = models.CharField(max_length=30) time_preference = ArrayField(ArrayField(models.CharField(max_length=30))) … -
how to use for loop in html template
i try to use for loop in html template to make a table but the probleme he add always column outside the table like in this pic !(https://ibb.co/Hz7ZRZd) i dont know why he continue directly out the table(if ther is one object only it's ok but when ther is more than 1 object in the ligne then this happned) what can i do ? thanks html templates <tr class="col-2"> <th>JOUR</th> <th>8-10</th> <th>10-12</th> <th>12-14</th> <th>14-16</th> <th>16-18</th> </tr> <tr class="col-2"> <td>SAMEDI</td> {% for ins in ob %} {% if ins.jour = 'S' %} {% if ins.heur = '1' and ins.jour = 'S' %} <td>{{ins}}</td> {% else %} <td> </td> {% endif %} {% if ins.heur = '2' and ins.jour = 'S' %} <td>{{ins}}</td>{% else %} <td> </td> {% endif %} {% if ins.heur = '3' and ins.jour = 'S' %} <td>{{ins}}</td>{% else %} <td> </td> {% endif %} {% if ins.heur = '4' and ins.jour = 'S' %} <td>{{ins}}</td>{% else %} <td> </td> {% endif %} {% if ins.heur = '5' and ins.jour = 'S' %} <td>{{ins}}</td>{% else %} <td> </td> {% endif %} {% endif %} {% endfor %} {% if a != 2 %} <td></td> <td></td> <td></td> <td></td> <td></td> {% … -
How to limit query within Django Admin.TabularInline with large scale data
I'm currently loading 50k records of data using admin.TabularInline, the page doesn't load due to time-out. I'm using Django version 1.9 and upgrade is not an option. I have already tried overriding the get_queryset to return only 10 records. class RemDetailInline(admin.TabularInline): model = RemDetail fields = ('rem_name', 'ben_name', 'payout_amount', 'payout_currency', 'status','type', 'date_created') readonly_fields = ('rem_name', 'ben_name', 'payout_amount', 'payout_currency', 'status', 'type', 'date_created') extra = 0 max_num = 0 show_change_link = True ordering = ['-date_created',] def get_queryset(self, request): queryset = super(RemDetailInline, self).get_queryset(request) ids = queryset.order_by('-id').values('pk')[:10] # limit 10 qs = RemDetailInline.objects.filter(pk__in=ids).order_by('-id') return qs I expect the output to return 10 records, instead the page timesout due to the high volume (50k records) -
How to handle an exception in a Django Middleware?
I have a problem with proper handling an exception in Django middleware. My exception: from rest_framework.exceptions import APIException from rest_framework.status import HTTP_403_FORBIDDEN class MyProfileAuthorizationError(APIException): def __init__(self, msg): APIException.__init__(self, msg) self.status_code = HTTP_403_FORBIDDEN self.message = msg And my Middleware: class PatchRequestUserWithProfile: def __init__(self, get_response): self.get_response = get_response def __call__(self, request, *args, **kwargs): patch_request_for_nonanon_user(request) if not request.user.profile: raise MyProfileAuthorizationError("You are not allowed to use this profile.") response = self.get_response(request) return response And this exception throws 500 instead of 403. How can i fix that? -
Can´t figure out how the taggit function works, i´ve implemented everything
I´ve implemented the taggit function from django-taggit. The tags are ok, i see it in my django admin and on my blog. But when i click on the tag on my blog, then i get an error. It doesnt filter with the tags, and thats my question. What I´m doing wrong? The Error message: Request Method: GET Request URL: https://www.code-reminder.com/python/ Raised by: blog.views.PostDetail My Code: Urls.py urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('about', views.about, name='about'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), re_path(r'^favicon\.ico$', favicon_view), path("tag/<slug:slug>/", views.tag, name='tag'), ] views.py def tag_detail(request, tag): posts = Post.objects.filter(tags__slug=tag) return render(request, 'tag_detail.html', {"posts": posts, "tag": tag}) models.py from taggit.managers import TaggableManager tags = TaggableManager() index.html <h2 class="card-title">{{ post.title }}</h2> <p class="card-text text-muted h6">{{ post.Author }} | {{ post.created_on}} | Tag: {% for tag in post.tags.all %} <a href="{{ tag.slug }}">{{ tag.name }}</a> {% empty %} None {% endfor %} </p> I want to display it on the same page index.html . So what I´m doing wrong? Please help -
Too many URL get request sent to server for django ModalForm in jquery
I am trying to open a django modalForm. Since the specific URL to this modalForm is depending on a tablerow I calculate the URL on a mouseenter event and sent the url to the server on a click event. However, on the click event is sends multiple get requests to the server instead of one. $('.dt-edit').on('mouseenter', function(evt){ $this = $(this); adresid = parseInt($this.parents('tr')[0].cells[13].innerHTML); console.log("AdresID: " + adresid) modaltmpurl = "{% url 'adres-update-modal' 0 %}".replace(/0/, adresid) $('.dt-edit').modalForm({ formURL: modaltmpurl }); }); The adresid value behaves as expected. So if my make my mouse enter each .dt-edit once and click each element once, the console log shows: AdresID: 16 AdresID: 17 AdresID: 15 AdresID: 13 AdresID: 14 whereas my server shows: [23/May/2019 11:07:37] "GET /adres/16/updatemodal/ HTTP/1.1" 200 7033 [23/May/2019 11:07:41] "GET /adres/16/updatemodal/ HTTP/1.1" 200 7033 [23/May/2019 11:07:42] "GET /adres/17/updatemodal/ HTTP/1.1" 200 7011 [23/May/2019 11:07:45] "GET /adres/16/updatemodal/ HTTP/1.1" 200 7033 [23/May/2019 11:07:45] "GET /adres/17/updatemodal/ HTTP/1.1" 200 7011 [23/May/2019 11:07:46] "GET /adres/15/updatemodal/ HTTP/1.1" 200 6955 [23/May/2019 11:07:49] "GET /adres/17/updatemodal/ HTTP/1.1" 200 7011 [23/May/2019 11:07:49] "GET /adres/15/updatemodal/ HTTP/1.1" 200 6955 [23/May/2019 11:07:49] "GET /adres/16/updatemodal/ HTTP/1.1" 200 7033 [23/May/2019 11:07:50] "GET /adres/13/updatemodal/ HTTP/1.1" 200 6958 [23/May/2019 11:07:53] "GET /adres/17/updatemodal/ HTTP/1.1" 200 7011 [23/May/2019 11:07:53] "GET /adres/16/updatemodal/ … -
Give extra custom link to table row field for show other table data in django-admin
I have product and product details table where i put product details in product inline form. Now i want to add one extra link in product display table to show particular product details to show -
How can I pass one parameters visible in URL and one more not with Django?
I want to pass 2 arguments thought url. The first one is an ID that I want to see in URL. The second is a counter but, this time, i don't want to see it in URL. This arguments come from a function "insert_inventory" and are going to "insert_resort". I don't know how i can do that. I'm trying with kwargs but that's didn't work. I'm using Django 2.2 urls.py path('insert_resort/<int:id_inventory>/', view_resort.insert_resort, kwargs={'id_inventory': 'id_inventory', 'cpt': 'cpt'}, name='insert-resort'), A part of insert_inventory function def insert_inventory(request) #Some code here... kwargs_resort = { 'id_inventory': id_inventory, 'cpt': 1, } return HttpResponseRedirect( reverse( 'insert-resort', kwargs=kwargs_resort, ) ) If someone understands my question and can redirect me on a good practice or a solution, i'll be thankful. -
How to handle reading, extracting & saving extremely large csv or excel data having an Angular client and a Django server
I've implemented a back-end functionality where one can upload a CSV or excel an file and then the server(Django API) will read and save all the data into the database but I feel like it's not the best approach and would like to get advise about this. I don't see the reason why the server is required to read and validate the CSV file while it's possible for the client(Angular app) to do that job. The client can read validate the file and the sends the data to the server. Then the server will do the rest of the job to save the data into the database. But I've come to think of it, suppose the file contains a million entries this means the server endpoint will be adding a million items. This will cause performance issues. What is the best approach to handle this? -
Cannot properly configure Django to run tests with nosetests
I am having problems running nosetests from the system command line. I installed django-nose and added it to settings.py: INSTALLED_APPS = [ ... 'django_nose', ] TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' Next, I've created .env file with the following contents: DJANGO_SETTINGS_MODULE=mysite.settings settings.py is in mysite, while .env is in .. Structure looks like this: /hay /mysite /tests .env manage.py Now, when I try to run nosetests while being in ., I am getting an error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I don't know what more to do with this. I thought that .env file will sort this thing out. -
On peut faire la conversion d'un projet développé avec zope to django ?
j'ai un projet développé avec zope 2 ,python 2.7 est ce que possible de faire la conversion vers django 2 python 3 ? -
Why does datetime__range work incorrectly?
date = datetime.datetime.today() I bring to the page a list of recent entries over the past week. For this I use a filter. I wondered why this variant does not work correctly (new entries appear after a while): filter(datetime__range=[date - datetime.timedelta(days=7), date]) But this variant works correctly: filter(datetime__gt=date - datetime.timedelta(days=7)) I wonder what's wrong with the first one? There are middleware class TimezoneMiddleware(object): def process_request(self, request): tzname = request.session.get('django_timezone') if not tzname: request.session['django_timezone'] = 'Europe/Kiev' tzname = 'Europe/Kiev' timezone.activate(pytz.timezone(tzname)) settings TIME_ZONE = 'UTC' -
Django makemessages MemoryError
I get an error while trying to run makemessages command for django translation. This is my settings.py file, with all the configuration find in the django manual. MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ] TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'django.template.context_processors.i18n', ], }, }, ] from django.utils.translation import ugettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('it', _('Italiano')), ) LANGUAGE_CODE = 'en' USE_I18N = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) However, when I run the following command python manage.py makemessages -l it I get this MemoryError exception. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/opt/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/opt/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/opt/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/opt/venv/local/lib/python2.7/site-packages/django/core/management/commands/makemessages.py", line 360, in handle potfiles = self.build_potfiles() File "/opt/venv/local/lib/python2.7/site-packages/django/core/management/commands/makemessages.py", line 402, in build_potfiles self.process_files(file_list) File "/opt/venv/local/lib/python2.7/site-packages/django/core/management/commands/makemessages.py", line 499, in process_files self.process_locale_dir(locale_dir, files) File "/opt/venv/local/lib/python2.7/site-packages/django/core/management/commands/makemessages.py", line 518, in process_locale_dir build_file.preprocess() File "/opt/venv/local/lib/python2.7/site-packages/django/core/management/commands/makemessages.py", line 117, in preprocess content = templatize(src_data, origin=self.path[2:], charset=encoding) File "/opt/venv/local/lib/python2.7/site-packages/django/utils/translation/__init__.py", line 220, in templatize return templatize(src, **kwargs) File "/opt/venv/local/lib/python2.7/site-packages/django/utils/translation/template.py", line 235, in templatize out.write(blankout(t.contents, 'X')) File "/opt/venv/local/lib/python2.7/site-packages/django/utils/translation/template.py", line 24, in … -
Model delete() and deserialized_object.save() calls don't work if called consecutively
I am trying to import json to my django webapp and its almost working fine except one problem. When I delete the objects 1-2 lines before calling deserialized_object.save() it works fine but if I call delete() and then save() consecutively it does not work properly. THIS WORKS FINE def builder_import(request, pk): if request.method == 'POST': file = request.FILES['myfile'] data = file.read() LogrepoIQLMap.objects.filter(logrepo__iql_index_builder__pk=pk).delete() for deserialized_object in serializers.deserialize("json", data): if object_should_be_saved(deserialized_object): deserialized_object.save() return redirect(reverse_lazy('indexbuilderapp:builder-update', kwargs={'pk': pk})) THIS DOES NOT WORK def builder_import(request, pk): if request.method == 'POST': file = request.FILES['myfile'] data = file.read() for deserialized_object in serializers.deserialize("json", data): if object_should_be_saved(deserialized_object): LogrepoIQLMap.objects.filter(logrepo__iql_index_builder__pk=pk).delete() deserialized_object.save() return redirect(reverse_lazy('indexbuilderapp:builder-update', kwargs={'pk': pk})) The first snippet works fine but the second snippet does not. In First case it deletes all entries and then uploads everything correctly in DB. But in second case it deletes and then uploads only one entry for some strange reason. May be it is some Synchronization issue but I thought django DB operations and well synchronized. What could be wrong? (I have followed following guide for serialization https://docs.djangoproject.com/en/1.11/topics/serialization) (edited) -
How to get the user details from social_django? And print all the details of all the users
I want to get the detail of all the users those who have login through google oauth and want to print all the details for my project. I am just getting the detail of the current user who have login using the google login.