Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django send email issue
I know there are similar questions to mine but my problem is weird.The email that I submit in the contact page doesn't get sent.Instead I get an email from my email. here is what I did in settings.py: EMAIL_HOST='smtp.gmail.com' EMAIL_HOST_USER= 'my gmail adress' EMAIL_HOST_PASSWORD= 'my password' EMAIL_PORT='587' EMAIL_USE_TLS=True in views.py -contact from django.shortcuts import render from django.core.mail import send_mail from django.conf import settings from .forms import contactForm # Create your views here. def contact(request): title = 'Contact Us' form = contactForm(request.POST or None) comfirm_message=None if form.is_valid(): name = form.cleaned_data['name'] comment = form.cleaned_data['comment'] subject = 'Message from a user of Archives Manager' emailFrom = form.cleaned_data['email'] message = '%s %s' % (comment, name) emailTo = [settings.EMAIL_HOST_USER] send_mail(subject, message, emailFrom, emailTo, fail_silently=True) title = "Thanks!" comfirm_message='Thanks for the message. we will get right back to you.' form=None context = {'title': title, 'form' : form, 'comfirm_message': comfirm_message, } template = 'contact.html' return render(request,template,context) and what I get in my gmail account is a message from my email adress not from the one I submited in EmailField()? from django import forms class contactForm(forms.Form): name = forms.CharField(required=False,max_length=100, help_text="100 is the maximum length" ) email = forms.EmailField(required=True) comment = forms.CharField(required=True,widget=forms.Textarea) -
How to do object-level-permission in django(or row-level-permission)?
How to do object-level-permission in django (or row-level-permission)? -
Stop executing if it is the case
$('.btn-process-request', node).bind('click', function(e){ e.preventDefault(); var data = {}; var fax_number_empty = {{ contract.request.customer.fax }} if (fax_number_empty == 0) { alert('Please, attach the fax number to your profile'); } alert('Hello! What is your name?'); if ($(this).data('reason')) { data.reason = prompt($(this).data('reason')); if (!data.reason.length && $(this).data('reason-required')) { alert($(this).data('reason-required')); return false; } } $.ajax({ url : $(this).attr('href'), type: 'POST', data : data, success: function(data, textStatus, jqXHR) { if (data.success) { if (data.redirect_to) { window.location.href = data.redirect_to; } else if (data.reload) { window.location.reload(); } } else { alert('Error! See console for details :('); console.error(textStatus, data); } }, error: function (jqXHR, textStatus, errorThrown) { console.error(textStatus, errorThrown); } }); return false; }); In this code, I've created the lines var fax_number_empty = {{ contract.request.customer.fax }} if (fax_number_empty == 0) { alert('Please, attach the fax number to your profile'); } I don't how to implement this correctly. I'd like say, ok, if contract.request.customer.fax is empty, then display an alert which will say 'Please, attach the fax number to your profile.' The most important thing here is to stop executing. In other words, what is bellow those lines would not be executed. Could anyone have time to tell me how to improve that code? P.S. Please don't be shy … -
Annotate not returning the expected results
I have a model here as below: class Project(models.Model): project_id = models.CharField(max_length=10, blank=False, primary_key=True) title = models.CharField(max_length=128, blank=False,) start_date = models.DateField(null=False) end_date = models.DateField(null=True) total_amount = models.DecimalField(max_digits=10, decimal_places=2) raised_amount = models.DecimalField(max_digits=10, decimal_places=2) cause = models.ForeignKey('Cause', on_delete=models.SET('cause not set')) ngo_id = models.ForeignKey('NGO', on_delete=models.SET('ngo not set')) zip = models.IntegerField(blank = True) reimagine_fees=models.DecimalField(max_digits=10, decimal_places=3,default=0.05) person_of_contact = models.CharField(max_length = 100) summary = models.TextField(blank = False) story = models.TextField(blank = True) fb_description=models.CharField(max_length = 301,blank=True) tax_exemption_available = models.BooleanField(default=False) banner = models.TextField(blank=True) team_member_id = models.ForeignKey(Team_Member, on_delete=models.SET('team member not set')) project_page_desc = models.CharField(max_length=300, blank=True) def __str__(self): return self.title I am trying to filter the Project objects according to the percetages of funding, that is, the ratio of raised_amount and total_amount... I am using annotate for this. However, the filter isn't giving the results as I expected it to give. My filter queries are: project_list = project_list.annotate(x=F('raised_amount')/F('total_amount')).exclude(x__gte=0.8) project_list = project_list.annotate(x=F('raised_amount')/F('total_amount')).exclude(x__lte=0.2) project_list = project_list.annotate(x=F('raised_amount')/F('total_amount')).exclude(x__lte=1, end_date__gte=datetime.date.today()) project_list is a dictionary of all the Project objects. Help me here... -
Prefetch related after many-to-one relation
I have the following (simplified) model structure: class Article(Model): @property def article_number(self) -> str: return self.attributes.get(masterdata_type__code='article_number').value class Attribute(Model): article = ForeignKey(Article, null=True, blank=True, related_name='attributes') masterdata_type = ForeignKey(Type, related_name='attributes') value = CharField(max_length=256, blank=True, db_index=True) class Type(Model): code = models.CharField(max_length=32) In the admin panel, I want to show a list of 100s of articles and show its article_number. This now result in 100s of database calls (which I can see using Silk monitoring), so I want to prefetch those objects. I tried the following solutions in the admin panel, but all didn't work. What is the proper way to reduce number of database calls here? I am using Django 1.8.14, with a PostgreSQL backend. Solutions that don't work: def get_queryset(self, request): queryset = super(ArticleSetAdmin, self).get_queryset(request) return queryset.prefetch_related('attributes__masterdata_type') Still 100s of database calls. def get_queryset(self, request): queryset = super(ArticleSetAdmin, self).get_queryset(request) return queryset.prefetch_related( Prefetch('attributes', queryset=Attribute.objects.select_related('masterdata_type'))) Still 100s of database calls. def get_queryset(self, request): queryset = super(ArticleSetAdmin, self).get_queryset(request) return queryset.prefetch_related( Prefetch('attributes', queryset=Attribute.objects.prefetch_related('masterdata_type'))) Still 100s of database calls. def get_queryset(self, request): queryset = super(ArticleSetAdmin, self).get_queryset(request) return queryset.select_related('attributes__masterdata_type') Error, since attributes is Many-to-One relationship to Article. -
Getting Error while installing djangorestframework - Permission denied: '/usr/lib/python2.7/site-packages/djangorestframework-3.6.3.dist-info'
I want to install Django rest framework in fedora-25 but when I run this command : pip install djangorestframework I'm getting following error: Collecting djangorestframework Using cached djangorestframework-3.6.3-py2.py3-none-any.whl Installing collected packages: djangorestframework Exception: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python2.7/site-packages/pip/commands/install.py", line 326, in run strip_file_prefix=options.strip_file_prefix, File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 742, in install **kwargs File "/usr/lib/python2.7/site-packages/pip/req/req_install.py", line 834, in install strip_file_prefix=strip_file_prefix File "/usr/lib/python2.7/site-packages/pip/req/req_install.py", line 1037, in move_wheel_files strip_file_prefix=strip_file_prefix, File "/usr/lib/python2.7/site-packages/pip/wheel.py", line 346, in move_wheel_files clobber(source, lib_dir, True) File "/usr/lib/python2.7/site-packages/pip/wheel.py", line 317, in clobber ensure_dir(destdir) File "/usr/lib/python2.7/site-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib64/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/usr/lib/python2.7/site-packages/djangorestframework-3.6.3.dist-info' You are using pip version 8.1.2, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. And when I try above command with sudo , getting following error Collecting djangorestframework Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f0011a7bf10>: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/djangorestframework/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f0013a4fe50>: Failed to establish a new connection: [Errno -2] Name or service … -
Bootstrap CSS - Info Box Alignment
I have the following bootstrap info box: <div class="alert alert-info" style="text-align: center" role="info"> <span style="font-size: 30px; vertical-align: middle; padding:0px 10px 0px 0px;" class="glyphicon glyphicon-info-sign alert-info" aria-hidden="true"></span> <span style="font-size: 13px; vertical-align: middle;" class="alert-info" role="info">Please help support your chosen charity <b>{{ request.session.chosenCharity }}</b> and the str8RED development by signing up for additional benefits.</span> </div> This creates the following box: As you can see it looks a little clumsy. I would like the "i" in the circle to be vertically centred in the blue box with the writing to its right but NOT over lapping like it currently does. I have tried using the django grid but it made the "i" and the writing look too far apart. I tried to use HTML tables but could not get it to match what I am after. Any thoughts on how to solve this would be greatly appreciated. -
I'm using django signals to get logged in user, but I'm having error saying "Signal receivers must be callable." I had made receiver though
in views.py im simply creating objects of Message class and did other stuff @python_2_unicode_compatible class Message(models.Model): user = models.ForeignKey(User, related_name='+', blank=True, null=True) message = models.TextField(max_length=1000, blank=True, null=True) date = models.DateTimeField(auto_now_add=True) conversation = models.ForeignKey(User, related_name='logged_in_user', blank=True, null=True) form_user = models.ForeignKey(User, related_name='+', blank=True, null=True) is_read = models.BooleanField(default=False) def __str__(self): return self.message @staticmethod def get_conversations(user): conversations = Message.objects.filter(user=user).values('conversation').annotate( last=Max('date')).order_by('-last') users = [] for conversation in conversations: users.append({ 'user': User.objects.get(pk=conversation['conversation']), 'last': conversation['last'], 'status': 'online' if hasattr(conversation, 'logged_in_user') else 'offline', }) return users def login_user(sender, request, user, **kwargs): Message(conversation=user).save() def logout_user(sender, request, user, **kwargs): try: u = Message.objects.get(conversation=user) u.delete() except Message.conversation.DoesNotExist: pass user_logged_in.connect(login_user) user_logged_out.connect(logout_user) Using django signals to get logged in user in a different way was quite easy and code worked in my project, But here I want to implement in different way -
Unicode decode error in Django Report Builder
So I am in the process of standing up a Django site that connects to four legacy DBs. From the admin panel in django everything works correctly. I am able to grab all the data. With the Report Builder GUI I can get most of them. But the most important one comes back with an error 500. It says that there is a unicode error at byte... Somewhere along the way it is unable to make the translation. I see a lot of people here with this problem but no real solutions for it. Where would I even begin to fix this??? -
Django language change after post request
I have this view in django which fetches post data from the form in another previous view. def sitexam(request): if request.POST: e_code = int(request.POST['engagement_code']) e_id = int(request.POST['exam_id']) return render(request, 'main/sitexam.html', {'title': 'SIT EXAM', 'qna': [e_code, e_id]}) Django translation is enabled and while testing on the sitexam view, it is POST request on the first time and if language is changed on the page it makes a GET request and can't access the context (qna) that I want in the template. How do I make the post data stay on language change on this view ? should I go for sessions or is there a better way to handle this situation ? -
How to edit Django FieldFile with S3 storage backend
I have the S3 storage backend set up and I am able to upload files to the S3 bucket. The config in settings.py looks like this: AWS_STORAGE_BUCKET_NAME = 'xxxxx' AWS_ACCESS_KEY_ID = 'xxxxxxxxxxxxx' AWS_SECRET_ACCESS_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxx' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' and the class in models.py: class Model (models.Model): name = models.CharField(max_length=50, null=False, blank=False) file = models.FileField(upload_to='models/%Y/%m/%d/') What I need is modify the file with an external program, which was possible with the default storage backend (using local disk) followingly: def modify_model(model): try: subprocess.check_call(["/usr/bin/program", model.file.path]) except: pass As the S3 backend does not support the path attribute, I am wondering how should I do it correctly? The error looks like this: >>> m.file.path Traceback (most recent call last): File "<console>", line 1, in <module> File ".../site-packages/django/db/models/fields/files.py", line 64, in _get_path return self.storage.path(self.name) File ".../site-packages/django/core/files/storage.py", line 111, in path raise NotImplementedError("This backend doesn't support absolute paths.") NotImplementedError: This backend doesn't support absolute paths. My first thoughts are saving the file locally, modifying it and then uploading the modified version. Is there any way to work with the files … -
My django query is very slow in givig me data on terminal
I have a users table which has 3 types of users Student, Faculty and Club and I have a university table. What I want is how many users are there in the specific university. I am getting my desired output but the output is very slow.I have 90k users and the output it is generating it takes minutes to produce results. My user model:- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from cms.models.masterUserTypes import MasterUserTypes from cms.models.universities import Universities from cms.models.departments import MasterDepartments # WE ARE AT MODELS/APPUSERS requestChoice = ( ('male', 'male'), ('female', 'female'), ) class Users(models.Model): id = models.IntegerField(db_column="id", max_length=11, help_text="") userTypeId = models.ForeignKey(MasterUserTypes, db_column="userTypeId") universityId = models.ForeignKey(Universities, db_column="universityId") departmentId = models.ForeignKey(MasterDepartments , db_column="departmentId",help_text="") name = models.CharField(db_column="name",max_length=255,help_text="") username = models.CharField(db_column="username",unique=True, max_length=255,help_text="") email = models.CharField(db_column="email",unique=True, max_length=255,help_text="") password = models.CharField(db_column="password",max_length=255,help_text="") bio = models.TextField(db_column="bio",max_length=500,help_text="") gender = models.CharField(db_column="gender",max_length=6, choices=requestChoice,help_text="") mobileNo = models.CharField(db_column='mobileNo', max_length=16,help_text="") dob = models.DateField(db_column="dob",help_text="") major = models.CharField(db_column="major",max_length=255,help_text="") graduationYear = models.IntegerField(db_column='graduationYear',max_length=11,help_text="") canAddNews = models.BooleanField(db_column='canAddNews',default=False,help_text="") receivePrivateMsgNotification = models.BooleanField(db_column='receivePrivateMsgNotification',default=True ,help_text="") receivePrivateMsg = models.BooleanField(db_column='receivePrivateMsg',default=True ,help_text="") receiveCommentNotification = models.BooleanField(db_column='receiveCommentNotification',default=True ,help_text="") receiveLikeNotification = models.BooleanField(db_column='receiveLikeNotification',default=True ,help_text="") receiveFavoriteFollowNotification = models.BooleanField(db_column='receiveFavoriteFollowNotification',default=True ,help_text="") receiveNewPostNotification = models.BooleanField(db_column='receiveNewPostNotification',default=True ,help_text="") allowInPopularList = models.BooleanField(db_column='allowInPopularList',default=True ,help_text="") xmppResponse = models.TextField(db_column='xmppResponse',help_text="") xmppDatetime = models.DateTimeField(db_column='xmppDatetime', help_text="") status = models.BooleanField(db_column="status", default=False, help_text="") deactivatedByAdmin = … -
How fix problems with adding pictures and objects in django-summernote?
I have model Specification with field description. I am tring to create form where user can create new Specification object by adding text, picture to description field. I have 2 problems. 1) When I add picture from computer I dont see it inside field however I see that picture in media_root. How to fix this problem?! 2) When I click submit button, it dont create new Specification object. It just show my form with content without editing. I thought next my code would be create new object and update list of objects. settings.py: INSTALLED_APPS = [ 'django_summernote' ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') MEDIA_URL = '/media/' models.py: class Specification(models.Model): ******* description = models.TextField(_('Description')) ******* forms.py: class SpecificationForm(forms.ModelForm): description = forms.CharField(widget=SummernoteInplaceWidget(attrs={'width': '100%'})) class Meta: model = Specification fields = ('description',) urls.py: urlpatterns = i18n_patterns( url(r'^summernote/', include('django_summernote.urls')), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py: def specification_add(request): data = dict() if request.method == 'POST': specification_form = SpecificationForm(request.POST) if specification_form.is_valid(): specification = specification_form.save(commit=False) ***Some code*** specification.save() data['form_is_valid'] = True specifications = Specification.objects.all() context = {'specifications': specifications} context.update(csrf(request)) data['html_specification'] = render_to_string('project/specification_list.html', context) else: data['form_is_valid'] = False else: specification_form = SpecificationForm() context = {'specification_form': specification_form} data['html_specification_form'] = render_to_string('project/specification_add.html', … -
Django query an unknown number of multiple date ranges
I have a form which allows a user to select users by multiple age ranges: 18-24, 25-34, 35-44 etc. Currently if a user selects the first two fields in the multiple selection list, the query will return users 18 - 34. If a user selects 18 - 24 year olds, and 35-44 year olds, it will include all ages from 18 - 44, when it should not include users aged 25-34. How would you approach including multiple range filters on a query without knowing the number of ranges you need to filter by prior to the users form selections? If you knew the number of age ranges the user was going to filter by I know you could chain range queries using Q. This is my current query: query = User.objects.filter( gender__in=genders, created__in=dates, data_source__in=sources, dob__range=[from, to] ) Thanks in advance. -
Too many values to unpack in python list
I got the below mention list as a web service [{'BatchNumber': '286270', 'CandidateId': '7126657', 'CandidateName': 'Namo ', 'NOSId': 'SSC/N3022', 'NOSName': 'Undertake data entry services', 'Project': 'PMKVY', 'QPID': 'SSC/Q2212', 'QPLevel': '4', 'QPName': 'Domestic Data Entry Operator', 'TPName': 'OrionEdutechPrivateLimited', 'TestDate': '01-Sep-2015', 'TestLocation': 'Kamrup', 'Theory': '0.00', 'TotalPratical': '85', 'TotalTheory': '35'}] I iterate through the list but got error notifying to many values to unpack therefore I tried enumerate method and faced TypeError: unsupported operand type(s) for +: 'int' and 'str'. I want my output in dictionary format like following 'BatchNumber': 286270 'CandidateID' : 7126657 and so on . please provide any solution thanks in advance. -
Django extending User Model which strategie i can use (Beginner ;) )
I want to add additional fields of information in my registration page like (address, phone number ... etc) and ask the user to browse documents on his computer in order to transmit them during registration. I saw that there are several ways to implement this How to Extend user model I have seen that there are several ways to customize the default User model, but I do not know which one to choose and how to set up the uploading of documents THANX FOR HELPIN ! -
Passing kwarg to view from form
Trying to change two similar function views into one which can take extra kwarg. The view should show extra tags when i use my form. As far as the query for the active post works, the form gives back the same result completely ignoring what i write into form. Class definition: class PostListView(ListView, FormMixin): model = Post paginate_by = 10 template_name = 'ak47/frontsite.html' form_class = TagForm def get_queryset(self): qs = super().get_queryset().active() if 'tags' in self.kwargs: tags = get_object_or_404(Tag, slug=self.kwargs['tags']) qs = qs.filter(tags__in=[tags]) return qs def get_context_data(self, **kwargs): kwargs.update({ 'tags': self.kwargs.get('tags', '') }) return super().get_context_data(**kwargs) Url to this view looks like this: url(r'^$', views.PostListView.as_view(), name='frontsite'), And form like this: <form class="navbar-form navbar-left" method="get" action="."> <div class="form-group"> <label>Look for posts with tag:</label> <input type="text" class="form-control" placeholder="Search" id="tag"> </div> <button type="submit" class="btn btn-default">find tag</button> </form> -
How can I filter by date to get this week vs previous week Counts from a QuerySet?
I have the following two annotated QuerySets which I have generated separately by extracting this_wk and prev_wk from a data set, then performing the annotation. I would like to merge them together before returning them. data = { 'this_wk': QuerySet([{'this_total': 3, 'dept': 2}, {'this_total': 2, 'dept': 1}, {'this_total': 1, 'dept': 3}]), 'prev_wk': QuerySet([{'prev_total': 2, 'dept': 3}])} Expected: QuerySet([{'this_total': 3, 'prev_total': None, 'dept': 2}, {'this_total': 2, 'prev_total': None, 'dept': 1}, {'this_total': 1, 'prev_total': 2, 'dept': 3}]), Alternatively, is there a way of aggregating this directly so that I go straight from a set of items with date fields? Here's how I am currently generating the two QuerySets: previous_items = Widget.objects.filter(start__gte=prev_start).filter(start__lte=prev_end) prev_ranking = previous_items.values('dept').annotate(prev_total=Count('dept')) this_items = Widget.objects.filter(start__gte=this_start ).filter(start__lte=this_end) this_ranking = this_items.values('dept' ).annotate(this_total=Count('dept') ).order_by('-this_total') Is there a way to chain these two annotations together so that I end up with a single QuerySet grouped and ranked for each Dept depending on how many Widgets it was used by this week, but also with an added field that says how many Widgets it was used by the previous week? I'm thinking something like this: items = Widget.objects.filter(start__gte=prev_start ).filter(start__lte=this_end ).annotate(prev_total=Count('dept') # can I restrict this to the previous week? ).annotate(this_total=Count('dept') # can I restrict this … -
How to change static and media directory for Django project that have 2 apps
This is a continuation for my previous question How to get hostname or IP in settings.py so that i can use it to decide which app's urls to use I am making a django application where it will have 2 apps. When you open www.webName.co.id it will use urls.py from app A, but when you open webName.co.uk it will use urls.py from app B. Basically my project will have 1 backend, multiple frontend urls and views, and each apps have their own models. But i am having problem with how Django decide which static folder and media root it is using. I want to change which static folder and media it is using depending on the www. Basically i want to use static and media folder in app A when you enter webName.co.uk, and another static and media folder in app B when you enter webName.co.uk The way i am going to do this is adding codes in middleware to change the settings for MEDIA_ROOT and STATICFILES_DIRS, but the documentation said i should not do this. How do i achieve what i wanted? thanks class SimpleMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): … -
sphinx + django, “commands out of sync; you can't run this command now”
I have a Sphinx stored procedure that is executed from Python (wrapped in Django). I get the error "commands out of sync; you can't run this command now"... what should i do? @cache_page(1800) def search(request, keyword=None, p=None): if not keyword: return redirect('/') if politics.is_sensitive(keyword): return redirect('/?' + urllib.urlencode({'notallow': keyword.encode('utf8')})) d = {'keyword': keyword} d['words'] = list(set(re_punctuations.sub(u' ', d['keyword']).split())) try: d['p'] = int(p or request.GET.get('p')) except: d['p'] = 1 d['category'] = request.GET.get('c', '') d['sort'] = request.GET.get('s', 'create_time') d['ps'] = 10 d['offset'] = d['ps']*(d['p']-1) try: res = Hash.objects.search(keyword, d['offset'], d['ps'], d['category'], d['sort']) except: return HttpResponse('Sorry, an error has occurred: %s' % sys.exc_info()[1]) d.update(res) # Fill info ids = [str(x['id']) for x in d['result']['items']] if ids: items = Hash.objects.list_with_files(ids) for x in d['result']['items']: for y in items: if x['id'] == y['id']: x.update(y) x['maybe_fake'] = x['name'].endswith(u'.rar') or u'BTtiantang.com' in x['name'] or u'liangzijie' in x['name'] or u'720p高清视频' in x['name'] if 'files' in x: x['files'] = [z for z in x['files'] if not z['path'].startswith(u'_')][:5] x['files'].sort(key=lambda x:x['length'], reverse=True) else: x['files'] = [{'path': x['name'], 'length': x['length']}] # pagination w = 10 total = int(d['result']['meta']['total_found']) d['page_max'] = total / d['ps'] if total % d['ps'] == 0 else total/d['ps'] + 1 d['prev_pages'] = range( max(d['p']-w+min(int(w/2), d['page_max']-d['p']),1), d['p']) d['next_pages'] = range( … -
Django: Logging in manage.py causes misleading exception and traceback
In manage.py file I want to send an email to admins each time a management command fails. The following code manage.py import logging logger = logging.getLogger('management_commands') try: execute_from_command_line(sys.argv) except Exception as e: logger.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info()) raise e is raising "The translation infrastructure cannot be initialized before the " django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time.` when the actual error in fact was ImportError: No module named django_inlinecss. My settings for the loggers are LOGGING = { ... 'handlers': { ... 'mail_admins': { 'class': 'django.utils.log.AdminEmailHandler', 'level': 'ERROR', 'include_html': True } }, 'loggers': { ... 'management_commands': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True } } } And the first part of the traceback is File "/usr/lib/python2.7/logging/__init__.py", line 1279, in _log self.handle(record) File "/usr/lib/python2.7/logging/__init__.py", line 1289, in handle self.callHandlers(record) File "/usr/lib/python2.7/logging/__init__.py", line 1329, in callHandlers hdlr.handle(record) File "/usr/lib/python2.7/logging/__init__.py", line 757, in handle self.emit(record) File "/usr/local/lib/python2.7/dist-packages/django/utils/log.py", line 128, in emit html_message = reporter.get_traceback_html() if self.include_html else None File "/usr/local/lib/python2.7/dist-packages/django/views/debug.py", line 384, in get_traceback_html return t.render(c) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 210, in render return self._render(context) This is how I ended up thinking there might be … -
Handle a click event in django-tables2
I am starting to use django-tables2 and I have added a column which should allow user to delete a record when the user clicks on the button. The code looks as follows: class ReviewTable(tables.Table): delete = tables.LinkColumn('review_delete', args=[tables.A('pk')], orderable=False, empty_values=(), verbose_name='') def render_delete(self, record): url = static('remove.png') href = '#' return mark_safe('<a href="' + href + '" Delete><img src="' + url + '"></a>') This basically enders the image fine in a column but all I can do is set the link to it. How can I get it to call some method where I can then filter by the record ID and delete the relevant record? Is this the correct way to do this? -
Should I iterate on django query set or over the variable?
I have a large dataset returned from django queryset and I want to iterate over it. Should I directly iterate over the queryset or store the results in a variable and iterate over it? for item in Model.objects.all(): do_something() or results = item in Model.objects.all(): for item in results: do_something() As far as I know, the variables are stored in heap and its safer, where as in case of iterating over queryset, the results will be stored in main memory. So which one is efficient in space and speed? -
Django Connection reset by peer
Good day, I have a problem, when i render video file in template <video autoplay muted> <sourcesrc="{{ video.oblozka_video_file.url }}" poster="{{ video.oblozka_video_preview.url }}" type="video/mp4"> </video> I have problem Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run self.finish_response() File "/usr/lib/python2.7/wsgiref/handlers.py", line 128, in finish_response self.write(data) File "/usr/lib/python2.7/wsgiref/handlers.py", line 217, in write self._write(data) File "/usr/lib/python2.7/socket.py", line 328, in write self.flush() File "/usr/lib/python2.7/socket.py", line 307, in flush self._sock.sendall(view[write_offset:write_offset+buffer_size]) error: [Errno 104] Connection reset by peer [19/May/2017 09:07:06] "GET /media/studios_videos/video/3/2/3e2df999-c34a-439b-b69a-94b4977a3d80.mp4 HTTP/1.1" 500 59 - Broken pipe from ('192.168.1.5', 55300) Please anybody help,me. -
Django-channel trying to send message on a channel returns error send attribute doesn't exist
I am receiving following error when calling django-channel object Channel("websocket.receive").send({ "room": message.channel_session['room'], "message": message['text'], }) AttributeError: 'Channel' object has no attribute 'send'