Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Graphene filter Foreign Model
I need to filter the object my request on the back-end base on permissions. For the following query : query { foos { id name bars { id name } } } There are permissions on foo and bar and I need to only return some foo and some bars. I know that I can use field lookups for foos class FooType(DjangoObjectType): class Meta: model = Foo class BarType(DjangoObjectType): class Meta: model = Bar class Query(object): foos = graphene.List(FooType) def resolve_foos(self, info, **kwargs): # id_list = some code to create a list of ids of possible foos return Foo.objects.filter(id__in=id_list) Say I have a list of possible bars, how can I do the same to filter on bar when requested by a graphql query ? -
Django, how serve media(users) files using nginx?
I'am struggling with my nginx configuration. Using docker-compose I deployed my Django app to vps. Static files works fine but I cant set up correctly media files. Below are my conf files: setting.py: STATIC_URL = '/static/' STATIC_ROOT = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = '/media/' nginx conf file: upstream web { ip_hash; server web:8000; } # portal server { location /static/ { autoindex on; alias /static/; } location /media/ { autoindex on; alias /home/www/book_store/media/; } location / { proxy_pass http://web/; } listen 8000; server_name localhost; } docker-compose.yml version: '2.1' services: nginx: #other commands volumes: - .:/code - ./nginx:/etc/nginx/conf.d - /static:/static - /media:/media depends_on: - web web: #other commands volumes: - .:/code - /static:/static - /media:/media error message when app trying to access media file (message from nginx container): ng01 | 2018/11/26 15:52:37 [error] 5#5: *6 open() "/home/www/book_store/media/default.png" failed (2: No such file or directory), client: XX.XX.XXX.XXX, server: localhost, request: "GET /media/default.png HTTP/1.1", host: "XXX.XXX.XX.XXX:8000", referrer: "http://XXX.XXX.XX.XXXX:8000/users/user/profile/" -
Bootstrapp Affix Function
If I copy the code from W3Schools to my webserver then the "sticky" menu works as long as I am referencing the CDN path for the script and stylesheet. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> If I change it to the location of the Bootstrap files that I have downloaded to the server then it doesn't work, although all other bootstrap styles and javascript functions work when referencing the local files. I have tried downloading the latest from Bootstrap as well. Sorry as I am probably missing something obvious, but is it possible to download the function and styles necessary for this to work? -
How to implement message notification in React App?
I am now building an application using React and Redux as the frontend and Django as the backend. What i am trying to realize is whenever an end user upload a file, all the end users that are related to this file should receive a notification. I am thinking of using websocket/socket.io but I am not sure if that works well with Django. Or any experience or suggestions of using any other technologies to implement the message notification function? -
How can I fix this error I'm getting when I want to run the server: 'django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.'
I am gettings this error when I'm trying to run the server (py manage.py runserver). I don't know what code I should upload because I think everything seems fine in my code... -
White Error Screen Appears when I try to update from form
I am getting a white error screen when I try to add an item via a form in python / django. I am trying to debug it but there is no information. Can somebody point me in the right direction? Models.py from __future__ import unicode_literals from django.db import models # Create your models here. from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.utils import timezone # Create your models here. class UserProfile(models.Model): image = models.ImageField(upload_to='images', default='Upload Picture') user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) address1 = models.CharField(max_length=255, blank=True) address2 = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=20, null=True) county = models.CharField(max_length=100, null=True) postcode = models.CharField(max_length=7, null=True) biography = models.TextField(max_length=280,blank=True) email = models.CharField(max_length=50, blank=True, null=True) phone = models.CharField(max_length=10, blank=True) dob = models.CharField(max_length=10, blank=True) gender = models.CharField(max_length=1, blank=True) facebook = models.CharField(max_length=50, blank=True, null=True) twitter = models.CharField(max_length=50, blank=True, null=True) instagram = models.CharField(max_length=50, blank=True, null=True) class KidProfile(models.Model): parent = models.ForeignKey(User, related_name='kids') name = models.CharField(max_length=255, null=True, blank=True) dob = models.CharField(max_length=10, null=True, blank=True) gender = models.CharField(max_length=1, null=True, blank=True) needs = models.CharField(max_length=3, null=True, blank=True) def __str__ (self): return self.name views.py from django.contrib import messages, auth from accounts.forms import UserRegistrationForm, UserLoginForm, FullUserDetailsForm, KidDetailsForm from django.core.urlresolvers import reverse from django.shortcuts … -
Reduce Django serialization time
I am doing queries for roughly 100,000 rows with approximately 40 column each. The columns are of combination of float, integer, datetime, and char. The query time is about two seconds, and serialization is taking forty seconds or more, whereas response building is about two seconds too. I am wondering how can I reduce serialization time for Django models? -
gitlab-ci with docker-compose with django
I have a project on django, in which I plan to use docker-compose.yml as an image delivery to the production server, we also conduct local development via this file. Through docker-hub and bitbucket images are collected without any problems. At the same time, I can pull them out of the docker-hub registry and launch them into docker SWARM via a specially prepared docker-compose-prod.yml file. docker-compose.yml looks like: version: '3' services: web: build: . command: ['./init.sh'] volumes: - .:/code ports: - "8000:8000" I wanted to build images on my own Gitlab server and use the internal registry, but I can't get to tag images in the correct way. I cannot specify the image name through the "image" directive in docker-compose because I use it for local development, and if this directive is specified, the code will not run locally. Here is .gitlab-ci.yml: services: - docker:dind before_script: - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY build: stage: build image: host:4567/foreing_agent/foreing_agent:$CI_COMMIT_TAG script: - docker-compose -f docker-compose-test.yml up - docker-compose build - docker-compose push host:4567foreing_agent/foreing_agent:$CI_COMMIT_TAG Maybe someone can tell me how to build the process of assembling and deploying code on a production server? Can someone be able to give examples of using .gitlab-ci … -
How I can get attribute from queryset using prefetch_related in Django?
I have following model and extracted queryset using prefetch_related as below. queryset=Light.objects.filter(certificate__name="A").prefetch_related('zone__namingzone') From this queryset, I want to get following data set. {"naming1":lpd1,"naming2":lpd2...} However, when I try to extract attribute from queryset as below, I get create_reverse_many_to_one_manager for i in queryset: print (i.zone.namingzone) What I want to get is naming attribute in naming table. Could anyone tell me how I can extract this? models.py class Certificate(models.Model): name=models.CharField(max_length=20) class Zone(models.Model): zone=models.CharField(max_length=20) class Light(models.Model): certificate=models.ForeignKey(Certificate, on_delete=models.CASCADE,related_name='certificate') zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='lightzone') lpd=models.IntegerField() class Meta: unique_together = (('certificate', 'zone'),) class Naming(models.Model): zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='namingzone') naming=models.CharField(max_length=20) -
Twilio programmable chat re-creates token every time and conversation not contnuing after page refreshing
Here is my code that returns chat user token that should be used to participate in conversation powered by twilio programmable chat. Took source from here. def token(request): identity = request.GET.get('identity', request.user.email) device_id = request.GET.get('device', 'default') # unique device ID account_sid = settings.TWILIO_ACCOUNT_SID api_key = settings.TWILIO_API_KEY api_secret = settings.TWILIO_API_SECRET chat_service_sid = settings.TWILIO_CHAT_SERVICE_SID token = AccessToken(account_sid, api_key, api_secret, identity=identity) # Create a unique endpoint ID for the device endpoint = "MiniSlackChat:{0}:{1}".format(identity, device_id) if chat_service_sid: chat_grant = ChatGrant(endpoint_id=endpoint, service_sid=chat_service_sid) token.add_grant(chat_grant) response = { 'identity': identity, 'token': token.to_jwt().decode('utf-8') } return JsonResponse(response) But after one successful conversation between two users I get Error: Channel member limit exceeded (I've set up two users on channel limit because I don't need a conference chat feature). I think it's because of token re-creating every time when page is loading. How should I write my code to allow the user to participate in a chat with his old token? I've tried to store generated token by this way: def token(request): identity = request.GET.get('identity', request.user.email) device_id = request.GET.get('device', 'default') # unique device ID account_sid = settings.TWILIO_ACCOUNT_SID api_key = settings.TWILIO_API_KEY api_secret = settings.TWILIO_API_SECRET chat_service_sid = settings.TWILIO_CHAT_SERVICE_SID token = request.user.twilio_token endpoint = "Qiwi-chat:{0}:{1}".format(identity, device_id) if token: token = token.encode('utf-8') else: token … -
Django Send Email
I am making a parking system with the option Paid and Not Paid, and only when chosen form paid, I want the system to send an email with the payment confirmation. I am able to send the email via console, but via the system will not and does not present any error models.py from django.db import models from django.core.mail import send_mail import math PAGO_CHOICES = ( ('Não', 'Não Pago'), ('Sim', 'Pago') ) class MovRotativo(models.Model): checkin = models.DateTimeField(auto_now=False, blank=False, null=False,) checkout = models.DateTimeField(auto_now=False, null=True, blank=True) valor_hora = models.DecimalField( max_digits=5, decimal_places=2, null=False, blank=False) veiculo = models.ForeignKey( Veiculo, on_delete=models.CASCADE, null=False, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) def horas_total(self): if self.checkout is None: return self.checkout == 0 else: return math.ceil((self.checkout - self.checkin).total_seconds() / 3600) def total(self): return self.valor_hora * self.horas_total() def __str__(self): return self.veiculo.placa def send_email(self): if self.pago is 'Sim': send_mail( 'Comprovante pagamento estacionamento', 'Here is the message.', 'estacioneaqui24@gmail.com', ['estacioneaqui24@gmail.com'], fail_silently=False, ) -
Apply Q object to one object
I have a complicated query in a Django model and I want to do two things: Get all objects that satisify the query Check if one object satisfies the query To do (1), I have a Q object encoding the query, and I just do Model.objects.filter(THE_QUERY) The query is something like THE_QUERY = Q(field_1__isnull=False) & Q(field_2__gte=2) & Q(field3=0) But I don't know how to reuse the query in THE_QUERY for (2). I want to have the predicate of the query in just one place and use that information to do (1) and (2), so that, if I ever have to change the query, both actions would do as expected. Is there a way to put the query in just one place? -
How to filter queryset by two lookups of the same field?
I'm building a tinder-like app. Here is a model represents review from one user to another: class Like(models.Model): like_from = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='outcome_likes') like_to = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='income_likes') is_positive = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.like_from} -> {self.like_to}' Now I'm trying to filter all matches and all I have is this code: def get_queryset(self): return CustomUser.objects.filter(income_likes__like_from=self.request.user, income_likes__is_positive=True)\ .filter(outcome_likes__like_to=self.request.user, outcome_likes__is_positive=True) # I also tried to go from the opposite side but # also had no idea how to get correct solution # Here should be some code to get intersection # of these two querysets's values lists # positive_likes_from = self.request.user.income_likes.all().filter(is_positive=True).values('like_from') # positive_likes_to = self.request.user.outcome_likes.all().filter(is_positive=True).values('like_to') But uncommented line here will return users that have any positive outcome likes with no guarantee that they will be addressed to the current user. I want to get a queryset of CustomUser model that have positive income and outcome likes with a current user on another side. Here is an solution of my problem that requires tons of SQL queries to the database: def get_queryset(self): positive_likes_from = self.request.user.income_likes.all().filter(is_positive=True) positive_likes_to = self.request.user.outcome_likes.all().filter(is_positive=True) result = [] for like in positive_likes_from: outcome_like_with_same_user_on_another_side = positive_likes_to.filter(like_to=like.like_from).first() if outcome_like_with_same_user_on_another_side: result.append((like, outcome_like_with_same_user_on_another_side)) return result -
how to access dictionary keys as index for list indexing in jinja2
i have a list selCategories and a dictionary categories. {{ selCategories }} // prints [1,1,0,0,1] {% for id,category in categories.items %} {{ selCategories.0 }} //prints 1 {{ selCategories.id }} //not printing anything {{ id }} //prints id values such as 1,2,3,4,5 <input type="checkbox" {% if selCategories.id == 1 %} checked {% endif %}>// empty checkbox {% endfor %} here selCategories=[1,1,0,0,1] categories={1:"Real",2:"education",3:"health",4:"food",5:"tourism"} how can i get the value of {{ selCategories.id }} so that i can use it in other html attributes -
A list and a form into the same django template
I have a one-page layout for a website, containing a list of latest posts in one section, and a contact form in another section. That means I need to feed both, the logic for the post list and the contact form, into the same template (home.html) I made it work as below, but that doesn't feel like the right solution... It's quite messy. Do you have a better approach? views.py def post_list(request): # Pull relevant posts from the database posts = Post.objects.filter(status='Published').order_by('-created') return posts def home_page(request): # Contact form logic if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(name, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found') messages.success(request, 'Mesage delivered') # Call the post_list() function posts = post_list(request) # Stuff it all into the home page template context = {'posts':posts, 'form':form} return render(request, "home.html", context) -
How I can delete Checked user in Django?
How I can delete Checked user in Django? After following answers on Stackoverflow, I've got the code below. However, I try to delete checked users from database by checked them then press delelte usig ajax but when press delete nothing happen at all also in server side it doesn't get 'POST' views.py def delete_list (request): if request.is_ajax(): selected_tests = request.POST['test_list_ids'] selected_tests = json.loads(selected_tests) for i, test in enumerate(selected_tests): if test != '': User.objects.filter(id__in=selected_tests).delete() return HttpResponseRedirect('/about') any.html <body> <button id="btn1" class="btn btn-round delete-btn" data-toggle="modal"> <i class="material-icons" action >delete</i> Delete </button> <div class="table-container"> <table id="fresh-table" class="table table-striped test-list"> <thead class="thead-table-list"> <tr> <th scope="col"> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input" id="checkall" type="checkbox" value=""> <span class="form-check-sign"> <span class="check"></span> </span> </label> </div> </th> <th scope="col">Id</th> <th scope="col">username</th> <th scope="col">email</th> </tr> </thead> <tbody> {% for test in list_wait %} <tr data-id="{{ test.id }}"> <td> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input check-ele" type="checkbox" value=""> <span class="form-check-sign"> <span class="check"></span> </span> </label> </div> </td> <td>{{ test.id}}</td> <td>{{ test.username}}</td> <td>{{ test.email}}</td> </tr> {% endfor %} </tbody> </table> {% csrf_token %} </div> <script type='text/javascript'> $("#btn1").click(function(){ var selected_rows=[]; $('.test-list').find('tr').each(function(){ var row=$(this); console.log(row.find('input[type="checkbox"]').is(':checked')); if (row.find('input[type="checkbox"]').is(':checked')) { console.log(row.attr('data-id')); selected_rows.push(row.attr('data-id')); }; }); var selected_rows = JSON.stringify(selected_rows); $.ajax({ url: "{% url 'delete_list' %}", type: 'POST', data: … -
Serializing Multiple API Fields into one. Django
I have a pre-defined API, like: { time : some_time, height : {1: 154, 2: 300, 3: 24}, color : {1: 'red', 2: 'blue', 3: 'green'}, age : {1: 27, 2: 324, 3: 1}, ... many, many more keys. } I have no control of this API, so cannot change its structure. Each integer key inside the sub dictionaries are linked and part of one record. For example the object that is 154 in height, is also colour: red and age: 27. I am aware one strategy to work with this is to have separate serialisers for each field. class MySerializer(serializers.ModelSerializer): # Nested serializers height = HeightSerializer() colour = ColourSerializer() age = AgeSerializer() etc, etc, etc But that still gives me messy data to work with, that requires lots of update() logic in the serializer. What I instead want to do is have one nested serializer that has access to the full request data, and can work with height, colour and age simultaneously and return me something like from the to_internal_value() method: { ['record' : 1, 'height': 154, 'colour' : 'red', 'age' : 27], ['record' : 2, 'height': 300, 'colour' : 'blue', 'age' : 324], ['record' : 3, 'height': 24, … -
Django ORM - How to calculate sum of array elements using PostgreSQL?
Here is what I have. class Array(Subquery): template = 'ARRAY(%(subquery)s)' class A(models.Model): ... class B(models.Model): a = models.ForeignKey(A) class C(models.Model): b = models.ForeignKey(B) b_sub = B.objects.filter(a=OuterRef('pk').annotate(items=Count('c').values('items') result = a.objects.annotate(items=Array(b_sub)) And I'm getting # >>> result.first().items [4, 6, 10] But I need the sum of all items(4+6+10)->20 for each A row. Like this # >>> result.first().items 20 Is it possible ? -
Getting Started With DJango REST Framework SyntaxError: invalid syntax
I am new to python and even newer to DJANGO. I've written two Python app before but it free form. I've started learning DJANGO Rest Framework this: https://www.django-rest-framework.org/tutorial/quickstart/ Copying exactly I've made it up to Testing our API, and running python manage.py runserver gives me: Performing system checks... Unhandled exception in thread started by <function wrapper at 0x10350c410> Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Library/Python/2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Python/2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Library/Python/2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 256, in check for pattern in self.url_patterns: File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/devindixon/Sites/Hearst/tutorial/tutorial/urls.py", line 18, in <module> from rest_framework import routers File "/Library/Python/2.7/site-packages/rest_framework/routers.py", line 25, in <module> from rest_framework import views File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 16, … -
How can I check the field value is unique in model django
I need that user can select only one photo with value 'COVER' in photo_tipo. Models.py class Listing(models.Model): ... class Photo(models.Model): PHOTO_TIPO_CHOICES = ( ('GALLERIA', 'Galleria'), ('COVER', 'Cover'), ('PLANIMETRIA', 'Planimetria'), ) photo_tipo = models.CharField( max_length=20, choices=PHOTO_TIPO_CHOICES, verbose_name='Tipo immagine', default='GALLERIA', ) Admin.py class PhotoInline(admin.TabularInline): model = models.Photo readonly_fields = ('image_tag',) @admin.register(models.Listing) class ListingAdmin(admin.ModelAdmin): inlines = [ PhotoInline, ] enter image description here Can i control user selection with error message, or remove 'COVER' from selection list if he have already chosen COVER photo ? I can't use unique=True in field because all model must have COVER photo. -
Django convert latitude and longitude into city and county
I need to convert longitude and latitude coordinates to city and county in website design. When user input the longitude and latitude as charfield. How could I convert it into string and get the city and county using google API in Django? Thank you -
How can I pre populate a textfield with one value based on a pk in django
Having a model of Preorder and Product I created an inline formset. A client can make a preorder(FK). My goal for this inline formset is to have only a pre populated value in a textfield and not all the values. My desired prepoppulated value is related with the pk of the client. Here is my view: class PreorderProductCreateView(LoginRequiredMixin, CreateView): model = Preorder fields=['preorder_date','client'] template_name='test/test.html' def get_context_data(self, **kwargs): data = super(PreorderProductCreateView, self).get_context_data(**kwargs) data['client']=Client.objects.filter(pk=self.kwargs.get('pk')) # print(Client.objects.filter(pk=self.kwargs.get('pk')))# if self.request.POST: data['formset'] = PreorderProductFormSet(self.request.POST)#bound the formset with data else: data['formset'] = PreorderProductFormSet()#empty formset return data def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super(PreorderProductCreateView, self).form_valid(form) def get_success_url(self, **kwargs): return reverse('client_list') I can fetch the pk of the current client successfully but I can not feed the returned client object to my data dictionary and finally can not load only the desired client object. Here is my url: url(r'^preorders/edit/(?P<pk>\d+)/$', views.PreorderProductCreateView.as_view(), name='preorder_edit'), Any suggestions? -
how to deploy django project and active virtualenv in cpanel
i am try to live my django project(hosting it) , my host provider company has accept python too , but i'm try to active virtual environment,and then install django , but i don't know how to active virtual env , what should i do with WSGI file location , thanks for advice -
Insert form Data in Django Database
When i have form data insert into django database but error on there built in function save(). Error is that form.save() AttributeError: 'FormName' object has no attribute 'save' Please anyone tell whats the problem and where and what the solution of that particular problem Thanks Regards Zeeshan -
how can I print side by side in a cycle for? (by the way I'm trying to do this in a django template)
<h3>Concepto:</h3> {% for j in li %} <h3> * {{ j.concepto_id }} de {{ j.fecha_realizado }} /</h3> {% endfor %}</center> this is a part of my template, what can I change in the last for to print side by side? and also I want to add decimal separator to the variable adicion