Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Haystack: ResultSet contains which object
We are using django-haystack along with elasticsearch as backend. I have indexed StoryPost which is our django-model stored in postgres. I am pretty much confused which object is being returned by the SearchQuerySet. >>> results=SearchQuerySet().all() >>> results[0] <SearchResult: kyc_connect_data_models.storypost (pk=u'429')> >>> results[0].object <StoryPost: <sarahh:First Channel POst>=QmVDXJvQXTZU9DWLy7kTAmyYwRvWao9PD98KPYvZ1JXRMG> In this a single result is of type SearchResult ok, but when I do .object is returns the exact model, so had it stored this model in elasticsearch db, is referring to it the original object in postgres db. If so how it maintains fast indexing then bcoz it would had to hit the db to fetch it? How it happens with pure elasticsearch? -
Speeding up django .exists()
I have a query TranslationStep.objects.filter(step_id=pk). I need to check if object is exist or not and if so, return object (or several objects). I have read that .exists() is more fastest way to do it, but I should make 2 requests. if TranslationStep.objects.filter(step_id=pk).exists(): return TranslationStep.objects.filter(step_id=pk) else: return None How can I optimise it? -
Having trouble with Ajax call in Django
I'm having some difficulty with an ajax call in a django app im working on. Here is my ajax call $("#form").submit( function () { var query = $("#query").val() $.ajax({ type: "GET", url: "/wolframquery/", data: { querytext: query }, success: function (data) { alert(data); } }); } and here is my View code def wolframquery(request): wolframID = '#########' query_string = request.GET.get('querytext') try: client = wolframalpha.Client(wolframID) res = client.query(query_string) text = str(next(res.results).text) return HttpResponse(text) except: text = str("Sorry, I couldn't find anything!") return HttpResponse(text) it takes the query string, then gets a response from the wolframalpha api and puts this into the text variable. Unfortunately it then breaks and doesn't return the variable. I've searched all over to no avail. Am quite new to Django development so probably missing something obvious here The debug console appears to show 3 errors. Error 1: ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine Error2: TypeError: 'NoneType' object is not subscriptable Error3: AttributeError: 'NoneType' object has no attribute 'split' -
How to show dynamic custom actions by selected custom filter in Django
class EvidenceFilter(SimpleListFilter): title = _('Evidence') parameter_name = 'evidence' def lookups(self, request, model_admin): return EVIDENCE_STATUS_CHOICES def queryset(self, request, queryset): if self.value(): if self.value() == 'pending': return queryset.filter(Q(profile__identity_verified='pending') & (Q(person_id_status='pending') | Q(person_selfie_status='pending') | Q(org_certificate_status='pending') | Q(org_taxid_status='pending'))) elif self.value() == 'accepted': return queryset.filter(Q(profile__identity_verified='pending') & ((Q(person_id_status='accepted') & Q(person_selfie_status='accepted')) | (Q(org_certificate_status='accepted') & Q(org_taxid_status='accepted')))) elif self.value() == 'rejected': return queryset.filter(Q(profile__identity_verified='pending') & ((Q(person_id_status='rejected') | Q(person_selfie_status='rejected')) | (Q(org_certificate_status='rejected') | Q(org_taxid_status='rejected')))) else: return queryset class EvidenceAdmin(admin.ModelAdmin): list_display = ('id', 'profile', 'person_id_status', 'person_selfie_status', 'org_certificate_status', 'org_taxid_status') list_filter = (EvidenceFilter,) actions = ['make_approved', 'make_denied'] class Meta: exclude = [] def get_actions(self, request): actions = super(EvidenceAdmin, self).get_actions(request) if self.list_filter[0].value()=='pending': if 'make_approved' in actions: del actions['make_approved'] if 'make_denied' in actions: del actions['make_denied'] return actions def make_approved(modeladmin, request, queryset): for evidence in queryset: evidence.profile.identity_verified = "approved" evidence.profile.save() make_approved.short_description = "Approve selected evidences" def make_denied(modeladmin, request, queryset): for evidence in queryset: evidence.profile.identity_verified = "denied" evidence.profile.save() make_denied.short_description = "Deny selected evidences" In get_actions function of EvidenceAdmin ModelAdmin class I am going to give special condition like that EvidenceFilter's selected value equal *pending*. if self.list_filter[0].value()=='pending': But I can't use the self.list_filter[0].value() to get the selected value of EvidenceFilter. I get the following error because of it. TypeError at /admin/securities/evidence/ value() missing 1 required positional argument: 'self' Any suggestions … -
Use firebase to send push notifications to an app via Django website
I want to use firebase to send push notifications to android app via Django website. Is there any way to do this? -
Datetime object won't work with weekday()
class Event(models.Model): day = models.DateField(blank=True, null=True) period = models.IntegerField(choices=period_choices) cart = models.CharField(choices=cart_choice, max_length=4) is_reserved = models.BooleanField(default=False) teacher = models.ForeignKey(User, blank=True, null=True) class ReservationForm(ModelForm): class Meta: model = Event fields = ('day', 'teacher', 'is_reserved', 'period', 'cart') widgets = {'teacher': forms.HiddenInput(), 'is_reserved': forms.HiddenInput(), 'period': forms.HiddenInput(), 'cart': forms.HiddenInput(), 'day': forms.HiddenInput()} I want to get the day of the week in order to sort events. I should be able to do this using Django's date filter - {% field.initial.day|day:"w" %} - but that doesn't return anything. So I wrote a template tag: @register.filter def the_day(value): return value.date().weekday() home.html {{ form.initial.day|the_day }} Nope: 'str' object has no attribute 'date' Alright, let's use dateparse @register.filter def the_day(value): answer = parse_date(value) return answer.weekday() Nope: Exception Type: TypeError at / Exception Value: expected string or bytes-like object Any ideas where to look? -
Django rest framework API testing. DRF inbuilt testing vs POSTMAN automated testing
What are the major advantages of writing tests using Django rest framework's APIRequestFactory/APIClient over POSTMAN automated API testing? Thank you. -
DoesNotExist: CustomerProfile matching query does not exist
class CustomerProfileFormCleaner(object): """ This objet centralises validation and normalizing of customer profile fields Should be run inside the form's clean function """ def __init__(self, form): self.form = form def clean(self): for name in self.form.fields: if hasattr(self, 'clean_%s' % name): try: value = getattr(self, 'clean_%s' % name)() self.form.cleaned_data[name] = value except ValidationError as e: self.form.add_error(name, e) def clean_first_name(self): return self.form.cleaned_data.get('first_name', '').title() def clean_last_name(self): return self.form.cleaned_data.get('last_name', '').title() # customerprofile def clean_street(self): return self.form.cleaned_data.get('street', '').title() def clean_city(self): return self.form.cleaned_data.get('city', '').title() def clean_zip_code(self): return self.form.cleaned_data.get('zip_code', '').upper() # employerprofile def clean_supervisor_name(self): return self.form.cleaned_data.get('supervisor_name', '').title() def clean_emp_street(self): return self.form.cleaned_data.get('emp_street', '').title() def clean_emp_city(self): return self.form.cleaned_data.get('emp_city', '').title() def clean_emp_zip_code(self): return self.form.cleaned_data.get('emp_zip_code', '').upper() def clean_agree_terms_and_cond(self): if self.form.cleaned_data.get('agree_terms_and_cond') == False: raise ValidationError( _('You must agree our terms and conditions') ) return self.form.cleaned_data.get('agree_terms_and_cond') def clean_bank_other(self): value = self.form.cleaned_data.get('bank_other') if self.form.cleaned_data.get('bank') == '000' and not value: raise ValidationError( _('A bank name must be provided') ) return value def clean_bankruptcy_date(self): value = self.form.cleaned_data.get('bankruptcy_date') if self.form.cleaned_data.get('had_bankruptcy') and value is None: raise ValidationError( _('Bankruptcy date is required') ) return value def clean_consumer_proposal_date(self): value = self.form.cleaned_data.get('consumer_proposal_date') had_cp = self.form.cleaned_data.get('had_consumer_proposal') if had_cp and value is None: raise ValidationError( _('Consumer proposal date is required') ) return value def clean_bank_account(self): ssn = self.form.cleaned_data.get('ssn') customer = CustomerProfile.objects.get(ssn=ssn) bank_account = self.form.cleaned_data.get('bank_account') … -
setting celery queues in django: unable to specify queues in settings.py
I have the following settings in django project's settings.py: CELERY_BROKER_URL = get_redis_url_with_db(1) CELERY_ACCEPT_CONTENT = ['json', 'pickle'] CELERY_TASK_SERIALIZER = 'pickle' CELERY_RESULT_SERIALIZER = 'pickle' CELERY_BEAT_SCHEDULE = { 'repush-countries-to-outs': { 'task': 'data.tasks.repush_countries_to_outs', 'schedule': timedelta(minutes=10), } } And everything works as expected. But when I add queue configuration: CELERY_ROUTES = { 'data.tasks.retry_fetching_out': { 'queue': 'fetch_outs' } } and restart Celery with the -Q fetch_outs setting, the task retry_fetching_out is ignored by workers. However, when I put the same configutation in the celery object itself like so: app = Celery('sourcery') app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.task_routes = { 'data.tasks.retry_fetching_out': { 'queue': 'fetch_outs' } } it starts working. All retry_fetching_out tasks are successfully picked up by workers from fetch_outs queue. What's wrong with the first way? -
Creating popups with django form
What will be the best way of creating django form popups .I have search online but could not fine help .Please help out . -
Expected type 'int', got 'IntegerField' instead Django
I am trying to get an object of class Guide to be the value of a calculation of other objects in the class. This is how far I have got in my code but got error Expected type 'int', got 'IntegerField' instead. How do I get this to work? Here is my code: class Guide(models.Model): guide_title = models.CharField(max_length=200) guide_category = models.CharField(max_length=70) guide_why = models.TextField() guide_how = models.TextField() user_current_conversion_rate = models.IntegerField(default=0) user_optimal_conversion_rate = models.IntegerField(default=0) user_monthly_visitors = models.IntegerField(default=0) user_average_order_value = models.IntegerField(default=0) user_increase_conversion_rate = models.IntegerField(default=0) @property def user_increase_conversion_rate(self): return int( (self.user_monthly_visitors*(self.user_optimal_conversion_rate/100))* self.user_average_order_value) - ((self.user_monthly_visitors*(self.user_current_conversion_rate/100))* self.user_average_order_value) -
django - aggregate json field specific keys and order by the aggregation
I have a model with the a field data of type JSONField from django.contrib.postgres.fields. The json structure is like so: {'aa': 1, 'bb': 2, 'cc': 4} I want to aggregate the sums of the aa and cc keys - so in this case, it will be 5. Also - i cannot promise that either aa or cc will be in the json. Is this possible? Thanks! -
implement django user (Staff member) to handle some user's informations
I am developing a website that allows the management of reservation of cars by users. I created a first app that manages user accounts such as : registration with email confirmation / login / logout ...etc i've created a special user that have staff permissions During registration, each new user must load pdf documents, these documents will then be verified by the staff user If the uploaded documents are good, this member sends to the user a PDF_contract to be signed electronically My question is How to display files uploaded by users for the staff user, so that he can check and send them back a Pdf document. My code: views.py from mysite.core.forms import SignUpForm, ProfileForm, DocumentForm from mysite.core.models import Profile from mysite.core.tokens import account_activation_token from django.views.generic.list import ListView from django.views.generic.detail import DetailView # Create your views here. def index(request): return render(request, 'index.html') @login_required def home(request): return render(request, 'home.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') else: form = SignUpForm() return render(request, 'signup.html', … -
Making models automatically in django?
Could you please tell me is there any method to create and migrate models automatically in django. Let me explain in brief: class Device1_Data(models.Model): created_at = models.CharField(max_length=30, null=True) Longitude = models.CharField(max_length=20, null=True) Latitude = models.CharField(max_length=20, null=True) Similary I wish that the same model should create for Device2_Data. and then again migrations also be taken place automatically. There should not be any necessity of running the python manage.py makemigrations. Is it possible guys?? -
django-modeltranslation removes text from models
This is my translation.py file: from modeltranslation.translator import translator, TranslationOptions from polls.models import Question, Choice class QuestionTranlationOptions(TranslationOptions): fields = ('question_text',) class ChoiceTranslationOptions(TranslationOptions): fields = ('choice_text',) translator.register(Question, QuestionTranlationOptions) translator.register(Choice, ChoiceTranslationOptions); models.py : from django.db import models from django.utils import timezone import datetime from django.utils.translation import ugettext_lazy as _ class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField(_('date published')) def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = _('Published recently?') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text When I open the app, the models' text is not visible. One of the questions is "Coke or Sprite?", but I can't see the text. What am I doing wrong? Python 3.4, Django 1.10 -
Django how to get in model the value from another model
How to get in django models class Another value of BlogPageGalleryImage image or foreign key or parental key? class BlogPage(Page): date = models.DateField("Дата публикации" , default=datetime.date.today ) body = RichTextField(blank=True) name = models.CharField(max_length=80, default='Лучший') class BlogPageGalleryImage(Orderable): page = ParentalKey(BlogPage, related_name='gallery_images') image = models.ForeignKey('wagtailimages.Image', on_delete=models.CASCADE, related_name='+') caption = models.CharField(blank=True, max_length=250) panels = [ ImageChooserPanel('image'), FieldPanel('caption'), ] class Another(BlogPage): page = ParentalKey(BlogPage, related_name='instagram_post') Image = BlogPageGalleryImage.objects.get(BlogPageGalleryImage.) caption = models.CharField(blank=True, max_length=250) panels = [ ImageChooserPanel('image'), FieldPanel('caption'), ] -
scp using slave node, jenkins on different vpc than web vpc, for django project
We are using jenkins to automate our deployment process jenkins master node is on deployment_vpc and we have a slave on our server_vpc and using ubuntu14.04 only(each machine). Only slave node can talk to our servers in server_vpc. We want to deploy the django project on the servers in server_vpc using slave node(only this node can communicate to those servers). I did research on the same: jenkins trigger build on another slave But answer is not descriptive enough to me. In short We want to build on jenkins master and scp that build on servers using slave node. So far We can pull the code to master node and make a build and can trigger slave node from jenkins web console. How can we accomplish this? Also suggest me if I am doing anything wrong? Thanks In advance -
Django Viwes---can't see the URL correctly
Inside an app called batches, I have set different url patterns. I have now 3 urls for batches, individuals and business names. It seems that when goind to the last 2 i am seeying only the info from batches all the time. Inside my app-batches i have 3 tables/classes. Please see my url pattern of the website: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^batches/', include('batches.urls')), url(r'^screenings/', include('screenings.urls')), url(r'^individuals/', include('batches.urls')), url(r'^businessnames', include('batches.urls')), ] This is what i have in my viewes: from __future__ import unicode_literals from .models import BusinessName from .models import Individuals from .models import Batches from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): all_Batches = Batches.objects.all() html = '' for batch in all_Batches: url = '/batches/' + str(batch.id) + '/' html += '<a href="#"' + url + '">' + str(batch.FileName)+ '</a><br>' return HttpResponse(html) def detail(request, batches_id): #parametrul asta batches_id tr sa se gaseasca in urls.py din app return HttpResponse("<h2>Details for Batches ID:" + str(batches_id) + "</h2") def index_businessname(request): all_BusinessNames = BusinessName.objects.all() html1 = '' for bn in all_BusinessNames: url = '/businessnames/' + str(bn.id) + '/' html1 += '<a href="#"' + url + '">' + bn.FullName + '</a><br>' return HttpResponse(html1) def detail_businessname(request, businessname_id): return … -
Django - How to implement authentication service in microservices architecture
Basically, I have several independent services. I want to build a service for authentication. When client get a token from authentication service. Client use it for further request to others services. Client need to attach that token in header of request. The services receiving token need to verify the token by sending it to authentication server. So all requests that clients make to protected routes need to be verified by authentication service. The thing is I do not know the best place to put the code that automatically sends token to authentication service and receive the result. Here is what i tried so far: I implemented a middleware like that: class VerifyTokenMiddleware(object): def process_request(self, request): if not request.META.get('HTTP_AUTHORIZATION'): return HttpResponse(status=404) auth_header = request.META.get('HTTP_AUTHORIZATION') token = auth_header[4:] response = requests.post(AUTH_URL, {"token": token}) if response.status_code == 400: return HttpResponse(status=403) return None However, the problem of my solution is every requests to services(not auth service) have to pass through that middleware. Therefore, client cannot access unprotected routes like before. Any help is extremely appreciated. :D I used django restframework jwt https://github.com/GetBlimp/django-rest-framework-jwt. -
django minimize frequent database load
I have question which could be generalized and applied to other problems, and would like to explore all the possibilities I've got in Django. let's say that I have classical eCommerce scenario. with it's relationships and basic field definitions class Basket: lines (ManyToManyField to BasketLine model) class BasketLine: product_option (ForeignKey to ProductOption model) quantity (IntegerField) class ProductOption: option_name (CharField) product (ForeignKey to Product model) price (DecimalField) class Product: name (CharField) In addition I have basket view which also accepts basket line modifications (like increment / decrement quantities, delete lines). In my view I've noticed pattern in which each time I try to perform modifications each time I 1) I query for user basket 2) I get target line to be modified (using basket.lines.filter) 3) I update target line which is modified (line.save()) with individual queries (using django ORM). For each operation this may end up retrieving ProductOption entry to check available quantities, and even go as deep as retrieve Product entry to handle prices. In the given situation what would be best options to leverage db querying and distribute load through the resources (more or less) evenly, like cache user basket, or even cache all the related model data (for … -
Django SMTP Error: authentication failed: authentication failure
I set up django email backend following way: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending e-mail. EMAIL_HOST = 'mytdl.de' # Port for sending e-mail. EMAIL_PORT = 25 # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = 'me@mytdl.de' EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') But sending emails with django-allauth will return following error: (535, b'5.7.8 Error: authentication failed: authentication failure') Testing the the settings with telnet mytdl.de 25 or Thunderbird as email client works fine. 2.7.0 Authentication successful But Django / SMTP stills throws that error. Django also tries to AUTH CRAM-MD5 and not AUTH LOGIN any ideas? -
Haystack: Does RealTimeSignalProcessor updates for updates to models.
Does HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' updates the index when any updates to model fields take place? In case I have used fields to filter/sort/search. -
How to build a profile view for users that also allows to update their information
I'm extending the Django default user model using OneToOne relation in Profile Model I want the user to have access to some profile information and allow him to updates them. I'm a beginner with Django so if u can show me the simplest way to do this that would be great. -
django & send_mail in docker leads to SMTPServerDisconnected
I setup a google email backend for django and all is working fine until i run the whole stuff in docker-compose containers. SMTPServerDisconnected at /events/register/4/ please run connect() first Request Method: GET Request URL: http://192.168.99.100:80/events/register/4/ Django Version: 1.11.3 Exception Type: SMTPServerDisconnected Exception Value: please run connect() first Exception Location: /usr/local/lib/python3.6/smtplib.py in send, line 359 Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.2 Python Path: ['.', '', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages', '/app'] Server time: Tue, 25 Jul 2017 11:07:45 +0200 Any idea what's going wrong here? Why is it disconnecting in a container? -
Filtering queryset by field='SPECIFIC_VAL' else field='ALL'
In my case i have 3 fields which is set dynamically ALL or a specific value. # note im using Q() function queryset = queryset.filter( Q(first_name=query) | Q(last_name=query) & Q(status=dynamic_status) & Q(gender=dynamic_gender) & Q(position=dymanic_position) ) status may Active/Inactive/All gender may Male/Female/All position may Position1/Position2/Position3/All How can i filter the queryset if one of these fields is set to ALL? Should i use IF ELSE condition and write multiple queryset filters or there is an elegant approach?