Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Activate specific 'image slider' only when corresponding left/right arrow is clicked using JavaScript in Django
I am working on a Django website where customers can book mobile barbers for appointments in their own home. I am a complete novice at JavaScript, but, as you can see from the images below, I have successfully created a working image slider for 'Johanson G' so customers can see demos of his haircuts when they click the left or right arrow on his profile. The problem I am having is: 1) The JS image slider code only seems to be applying to the first barber profile on the page, in this case, 'Johnason G'. As you can see 'William Despard's' images aren't even being hidden and are displaying below his profile picture. 2) I don't know how to specify that when a specific barber profile's left or right arrow is clicked only THAT profiles image slider is activated. For example, I don't want every barber's demo images being displayed when an arrow is clicked on just one barber profile. I imagine the solution for this will be including {{BarberProfile.id}} in each image's and arrow's 'id' and then somehow creating a rule where only the corresponding slider activated when the arrow is clicked? Any help or insight would be much … -
Get array of related objects django
I have this models: class Project(models.Model): And class Group(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name = "projects") I want to be able to retrieve projects groups. I tried something like this: print(project.groups) but got an error: 'Project' object has no attribute 'group' What do I do? -
Django ChoiceField always invalid or empty
I have a ChoiceField in a form and want to save its value in a model. The problem is that the form is never valid if the field is required. When I set required to False, the form is valid but does not contain any data - it's just blank. models.py: class CVSS(models.Model): av = models.CharField( max_length=10, null=True, ) forms.py: class CVSSForm(forms.ModelForm): AV = [ (u'N', u'Network'), (u'A', u'Adjacent'), (u'L', u'Local'), (u'P', u'Physical'), ] av = forms.ChoiceField( # required=False, widget=forms.RadioSelect(), choices=AV, ) class Meta: model = CVSS fields = ['av',] views.py: def edit(request, fid): cvss = get_object_or_404(CVSS, finding_id=fid) cvss_form = CVSSForm(instance=cvss) if request.method == 'POST': cvss_form = CVSSForm(request.POST, instance=cvss) if cvss_form.is_valid(): cvss_form.save() -
failed to query database with filter in django 2.0
I'm developing a blog app with django2.0. in the models layer, I defined a class Post, and defined a attribute created_time with DateTimeField, then I tried to query the posts based on the created_time with two arguments year and month, but finally it turns out there is no object got from the query. What seems to be the problem? 1.blog/models.py class Post(models.Model): ... created_time = models.DateTimeField() ... 2.blog/views.py def archives(request, year, month): post_list = Post.objects.filter(created_time__year=year, created_time__month=month). order_by('-created_time') print('Year:{0}.\nMonth:{1}'.format(year,month)) count = 0 for a in post_list: count += 1 print("I've found {} post here!".format(str(count))) return render(request, 'blog/index.html', context={'post_list': post_list}) 3.blog/urls.py urlpatterns = [ ... url(r'^archives/(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/$',views.archives,name='archives'), ] templates/blog.index.html <li><a href="{% url 'blog:archives' date.year date.month %}">{{date.year}}年{{date.month}}月</a></li> In the database I've added lots of post, but finally the console output is like: **Why******? Note that, if I remove one argument created_time__month=month in view archives() as below, it can get the correct query results. def archives(request, year, month): post_list = Post.objects.filter(created_time__year=year).order_by('-created_time') -
UpdateView creates new objects instead of updating them
As the title says, when I try to use the UpdateView of a Parend Model with multiple Child Models to update them, instead of simply updating them, it creates new objects instead of updating them. I shouldn't have an issue with the form, models or anything because everything else is working, and I can edit the Parent Model, but the problem seems to be at the form_valid() method of my views.py. Here's the relevant code: (Entrada = Parent Model, BalaMateriesPrimeres = Multiple Child Model) class EntradaUpdateView(LoginRequiredMixin, UpdateView): model = Entrada fields = [...] template_name_suffix = '_update' def form_valid(self, form): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) qs = BalaMateriesPrimeres.objects.filter(num_entrada=self.get_object()) formsets = BalaMateriesPrimeresFormSet(self.request.POST, queryset=qs) if form.is_valid(): form.save() if formsets.is_valid(): instances = formsets.save(commit=False) for instance in instances: instance.instance = self.object instance.num_entrada = Entrada.objects.get(pk=self.object.id) instance.save() return super(EntradaUpdateView, self).form_valid(form) Seems like I'm missing a piece of the puzzle but I cannot figure out what -
ProgrammingError: relation "django_session" does not exist
Got this error after changing my database from sqlite to postgresql. I've made all my settings changes: Here's my settings: DATABASES = { 'default': { 'ENGINE': "django.db.backends.postgresql_psycopg2", 'NAME': "postr1", 'USER': "zorgan", 'PASSWORD': config('DB_PASSWORD'), 'HOST': "localhost", 'PORT': '', } } as well as performing makemigrations and migrations which were all successful. So I'm able to succesfully start my local server: System check identified no issues (0 silenced). May 15, 2018 - 08:59:39 Django version 1.11.8, using settings 'draft1.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. however when I go to the site it returns this error: ProgrammingError at /news/ relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... Any idea what the problem is? -
Submitting button inside a form selenium + python
I have this form which contains a button with some dynamic value, when I click on it it should add the product to the checkout page. Here is the html form : <form id="form-id" action="/send/" method="POST"> {% csrf_token %} <button class="add-to-cart-link" type="submit" name="product" value="{{p.id}}" > <input type="hidden" name="product_name" value="{{p.name}}"> <input type="hidden" name="product_price" value="{{p.lst_price}}"> Add to cart</button> </form> And here is my what I am doing with selenium: bon_commande = self.selenium.find_element_by_xpath("//button[@name='product' and @value='37']/parent::form") bon_commande.submit() And thanks for the help ! -
Post method inside a post method
I have the following code: <form class="square" action="{% url 'interface:modify_device_perform' %}" method="post"> {% csrf_token %} <div class="form-group"> <label>ID device</label> <input class="form-control" name="device_id" value="{{ device.id }}" readonly /> </div> <div class="form-group"> <label>Device name</label> <input class="form-control" name="device_human" value="{{ device.human_id }}" placeholder="Example: Box 2" /> </div> <div class="form-group"> <label>Associated patient</label> {% if device.user_set.get.id != '' %} <input class="form-control" value= "{{ device.user_set.get.id }}" readonly> </input> {% else %} <input class="form-control" value= "No patient" readonly> </input> {% endif %} </div> <div class="form-group"> <label>Device position</label> <select name="position_id" class="form-control"> {% for position in position_list %} {% if position == device.position %} <option selected="selected">{{ position.id }}</option> {% else %} <option>{{ position.id }}</option> {% endif %} {% endfor %} {% if device.position == None %} <option selected="selected"> No position </option> {% else %} <option> No position </option> {% endif %} </select> </div> <div class="form-group square_button"> <button class="btn btn-warning btn-md form-control" type="submit"> Modify Device </button> </div> </form> This represents the following: The problem is that I want to add a button on the right of No patient that makes a post request, making possible to remove a patient associated in case it has one. How I can add that post request inside a post request? -
Add mutiple values to Django Foreign Key
I have the following model structure: class Answer(models.Model): id = models.IntegerField(primary_key=True) answer_text = models.CharField(max_length=150) def __str__(self): return self.answer_text class Question(models.Model): question_text = models.CharField(max_length=150) choices = models.ForeignKey(Answer, on_delete=models.CASCADE, related_name='choices') answer = models.OneToOneField(Answer, on_delete=models.CASCADE) def __str__(self): return self.question_text I have registered both the models on admin. But when I try to add multiple choices to a question in the admin, it does list any other answers. See the attached screenshot. I am unable to add multiple choices for a question. When I click the green + button, it does not list all possible answers. -
How to connect Android Web Apps to a Django development server on an Android USB device
I have a python3 application running on Django 127.0.0.1:8000 and I want to access it via an Android Webview Application on an actual Android device not an AVD or Genymotion VM. -
AngularJS ng-if directive using a function not returning a value
I'm still pretty new to AngularJS. Following multiple tutorials online, I used a javascript function inside a ng-if directive to validate whether a group name already exists in an array. If it does, the ng-if block is skipped for the next ng-repeat iteration. If it doesn't, add the group name to an array and create the ng-if block. This is what the HTML code looks like in the partial: HTML <span ng-if="checkGroups(service.group.name)"> <!--Make nested list--> </span> This is a simplified version of the javascript: JAVASCRIPT (function () { 'use strict'; MainApp.controller('MainController', [ '$scope', 'Filters', 'helper', '$timeout', '$filter',function( $scope, Filters, helper, $timeout, $filter) { var MainCtrl = this; //Function to check group array variable $scope.usedGroups = []; $scope.checkGroups = function(name) { var isValid = true; for(var i = 0; i < $scope.usedGroups.length; i++) { if($scope.usedGroups[i] == name){ isValid = false; break; } } if(isValid == true){ $scope.usedGroups.push(name); console.log($scope.usedGroups); } return isValid; } } ]); })(); I've used console.log() to return the values and I do get an array with the group names inside as well as a true or false value being returned. The issue is the ng-if function seems to only return false. If I switch the directive function to … -
django detect user login in another tab
Is there anyway in django that if user has two open tabs, both logged out, then logs in in one tab, tell that he has logged in in another tab? I mean something like github that tells you you have signed in, please refresh the page. The problem is now If I login in one tab and then in the second tab, I get csrf token missing incorrect. -
What is the purpose of return statement with (**) [duplicate]
This question already has an answer here: What does ** (double star/asterisk) and * (star/asterisk) do for parameters? 15 answers I am reading about Django serialization class SnippetSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) code = serializers.CharField(style={'base_template': 'textarea.html'}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Snippet.objects.create(**validated_data) Why do we need ** in return statement? -
Django2: Submit and store blobs as image files
I have made a few Django projects after having read the tutorial but I am by no means an expert in Django. I am trying to take a screenshot of the current page and store it (if one does not exist). To achieve this, we require a few things: function to get screen shot of current page function to async post this image to a view which should store it view that stores the posted image However, the screen shot function results in a Blob and I am having trouble getting a Django view to properly handle this. A demo project is available here: https://gitlab.com/SumNeuron/so_save_blob Function for screenshot const screenshot = (function() { function urlsToAbsolute(nodeList) { if (!nodeList.length) { return []; } var attrName = 'href'; if (nodeList[0].__proto__ === HTMLImageElement.prototype || nodeList[0].__proto__ === HTMLScriptElement.prototype) { attrName = 'src'; } nodeList = [].map.call(nodeList, function (el, i) { var attr = el.getAttribute(attrName); if (!attr) { return; } var absURL = /^(https?|data):/i.test(attr); if (absURL) { return el; } else { return el; } }); return nodeList; } function addOnPageLoad_() { window.addEventListener('DOMContentLoaded', function (e) { var scrollX = document.documentElement.dataset.scrollX || 0; var scrollY = document.documentElement.dataset.scrollY || 0; window.scrollTo(scrollX, scrollY); }); } function capturePage(){ urlsToAbsolute(document.images); … -
How to detect error when not connected to mail server from Django?
I have the following in my settings.py: EMAIL_HOST = 'mail.domain.com' EMAIL_HOST_USER = 'user@domain.com' EMAIL_HOST_PASSWORD = '******' EMAIL_PORT = 567 EMAIL_USE_TLS = True I have the following code to send email: email = EmailMessage() email.subject = subject email.body = body email.from_email = from_email email.to = to email.attach(file_name, pdf, 'application/pdf') email.send() Sometimes our server is down and there is no way for me to detect if the mail was sent or not. One way I can think of is to show Mail not sent error when Django cannot connect to mail server. How can I detect a failed connection to the server? -
How to pass choice display name to model serialize in Django REST framework?
My env is Django 2.0.3, DRF 3.8.2 and Python 3.6.4. I have a model in serializers.py: class TransferCostSerializer(serializers.ModelSerializer): def to_representation(self, instance): field_view = super().to_representation(instance) if field_view['is_active']: return field_view return None class Meta: model = TransferCost fields = ('id', 'destination', 'total_cost', 'is_active',) Where destination field is choice field of 3 elements: DESTINATION = ( ('none', _('I will drive by myself')), ('transfer_airport', _('Only from airport')), ('transfer_round_trip', _('Round trip')), ) This is my models.py: class TransferCost(models.Model): destination = models.CharField( _('Transfer Destination'), choices=DESTINATION, max_length=55 ) total_cost = models.PositiveIntegerField( _('Total cost'), default=0 ) is_active = models.BooleanField(_('Transfer active?'), default=True) class Meta: verbose_name = _('Transfer') verbose_name_plural = _('Transfers') def __str__(self): return _('Transfer {}').format(self.destination) ..And I return JSON like this: [ { id: 1, destination: "transfer_airport", total_cost: 25, is_active: true }, { id: 2, destination: "transfer_round_trip", total_cost: 45, is_active: true } ] How to return destination field with his display name? For example: [ { id: 1, destination_display: "Only from airport", destination: "transfer_round_trip", total_cost: 25, is_active: true }, { id: 2, destination_display: "Round trip", destination: "transfer_round_trip", total_cost: 45, is_active: true } ] Would be great to have something like get_FOO_display() in serializers.py, but it's not working. -
Couldn't find the the 3rd party app " django.core.exceptions.ImproperlyConfigured:
When I access my list of instance, I getdjango.core.exceptions.ImproperlyConfigured: error. My view code is bellow: from constance import LazyConfig from testDemo02 import settings from django.http import HttpResponse def list_constance(request): config = LazyConfig() setting_list = [] for key, options in getattr(settings, 'CONSTANCE_CONFIG', {}).items(): default, help_text = options[0], options[1] data = {'key': key, 'default': default, 'help_text': help_text, 'value': getattr(config, key)} setting_list.append(data) return HttpResponse(setting_list) when I access the api, I get bellow error: ... File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/constance/backends/database/__init__.py", line 13, in __init__ from .models import Constance File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/constance/backends/database/models.py", line 9, in <module> raise ImproperlyConfigured("Couldn't find the the 3rd party app " django.core.exceptions.ImproperlyConfigured: Couldn't find the the 3rd party app django-picklefield which is required for the constance database backend. -
Django Extending model
I'm just wanting to know how to extend a model in Django without needing to create new database tables or rows. I have two models. SSALi with a unique ticker and date, and NELi with a ticker and a date that are together unique. I want a model or function called NN_feed that has all of the attributes of both models,EG sentiment, and prediction. The below works but it has created a new table that I need to join for every row and date. Is there a way to do this without extra database tables and just pull from the existing data? from django.contrib.postgres.fields import JSONField from django.db import models import datetime # Create your models here. class SSALi_Report(models.Model): date = models.DateField() ticker = models.CharField(max_length=10,default='NA') market = models.CharField(max_length=250,default='NA') price = models.FloatField() prediction = models.FloatField() def __str__(self): return str(self.date) + " - " + str(self.ticker) class NELi_Report(models.Model): date = models.DateField() ticker = models.CharField(max_length=10,default='NA') sentiment = models.FloatField(default='0.0') clout = models.FloatField(default='0.0') topNews = JSONField(default='{}') def __str__(self): return str(self.date) + " - " + str(self.ticker) class TopStock(models.Model): ticker = models.CharField(max_length=10,default='NA') name = models.CharField(max_length=200,default='NA') currentPrice = models.FloatField(default='0.0') date = models.DateField(default=datetime.date.today) # need to add company name def __str__(self): return str(self.date) + " - " + … -
Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused
I am using rabbitmq server in Django 1.8 on centos. When I restart the rabbitmq-server, operation get complete. Shows message restart ok. But when I see the status it shows following output. Starting node rabbit@bynrySystem ... Error: unable to connect to node rabbit@bynrySystem: nodedown DIAGNOSTICS attempted to contact: [rabbit@bynrySystem] rabbit@bynrySystem: * connected to epmd (port 4369) on bynrySystem * epmd reports: node 'rabbit' not running at all no other nodes on bynrySystem * suggestion: start the node current node details: - node name: 'rabbitmq-cli-59@bynrySystem' - home dir: /var/lib/rabbitmq - cookie hash: f/MoFCCKTONVCYhIDLxvew== When I run a task it gives following error. consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Please help. Thanks. -
SSL: TLSV1_ALERT_PROTOCOL_VERSION when I install django-constance
I can not install the django-constance. Steps to reproduce $ pip3 install django-constance Collecting django-constance Could not fetch URL https://pypi.python.org/simple/django-constance/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:645) - skipping Could not find a version that satisfies the requirement django-constance (from versions: ) No matching distribution found for django-constance System configuration Django version: $ django-admin --version 1.11.1 Python version: $ python3 --version Python 3.5.2 $ pip3 --version pip 9.0.1 from /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (python 3.5) -
How to apply/set a permission to an User
I have a Car model in my car_store app. class Car(models.Model): ... class Meta: permissions = (('can_buy', 'User can buy this car'),) Right now I have a custom User model in my accounts app which is: from django.db import models as _models from django.contrib.auth.models import AbstractBaseUser class User(AbstractBaseUser): email = models.EmailField() .... def has_perms(self, perm, obj=None): return True def has_module_perms(self, app_label): return True and later I would simple make use of PermissionRequiredMixin for my view: from django.contrib.auth.mixins import PermissionRequiredMixin from django.views.generic import ListView class CarListView(PermissionRequiredMixin, ListView): permission_required = ('car.can_buy',) The question is django does not offer any type of self.set_perm(self, perm) or set_perm(some_user, perm)? If not, what would be the simplest way to implement it? Should I simply do something like this? class User(AbstractBaseUser): perms = [] def set_perm(self, perm): self.perms.append(perm) def has_perm(self, perm): return self.perms.count(perm) I couldn't find nothing that describes how to set a perm to an user (except third-party django-guardian - assign_perm()). Neither a Full Example from django docs talks about how to set a perm to the User. There's even this Answer, but he doesn't talk about setting the perm to the user, but just how to check for a perm. -
django file download size keeps changing
following is file download code @api_view(['GET']) @permission_classes((AllowAny,)) def download_latest_pattern(request): latest_pattern = Pattern.objects.latest() if latest_pattern is not None: try: with open(latest_pattern.locate, 'rb') as db: response = HttpResponse(db, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=%s.db' % latest_pattern.version response['Content-Length'] = os.path.getsize(latest_pattern.locate) return response except FileNotFoundError: return Response(status=404) return Response(status=404) i downloaded files repeatedly but file size changed periodically following is my download list how can i solve the problem??? can i change nginx.conf? -
Diagnosing Memory leak in boto3
I have a celery worker running on Elastic Beanstalk that polls a SQS queue, gets messages (containing S3 file names), downloads those files from S3 and processes them. My worker is scheduled to run at every 15 seconds but due to some reason the memory usage keeps on increasing with time. This is the code I'm using to access SQS def get_messages_from_sqs(queue_url, queue_region="us-west-2", number_of_messages=1): client = boto3.client('sqs', region_name=queue_region) sqs_response = client.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=number_of_messages) messages = sqs_response.get("Messages", []) cleaned_messages = [] for message in messages: body = json.loads(message["Body"]) data = body["Records"][0] data["receipt_handle"] = message["ReceiptHandle"] cleaned_messages.append(data) return cleaned_messages def download_file_from_s3(bucket_name, filename): s3_client = boto3.client('s3') s3_client.download_file(bucket_name, filename, '/tmp/{}'.format(filename)) Do we need to close client connection in boto3 after we're done with the process ? If so, how can we do it ? -
python django error NoReverseMatch Exception Value: Reverse for 'updatecontact' with no arguments not found
i have a function that update data on the db here is my url url.py url(r'updatecontact/(?P\d+)/$',views.updatecontact,name="updatecontact"), template. Update i am getting the error: Exception Type: NoReverseMatch Exception Value: Reverse for 'updatecontact' with no arguments not found. 1 pattern(s) tried: ['updatecontact/(?P\d+)/$'] -
Django-social-auth get google id token
For a school project we are creating an timetable application. Because our school uses google, we decided to use the google authentication for our application. To access our API I need an id token. But I'm unable to get the id token from google. I'm using django with django-social-auth thanks in advance