Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django render to PDF with foreign key
I want to render to PDF the nome of pavimento on AvariaAdmin, and i really dont know how to do that. http://prntscr.com/mmm5eo MY models class Avaria(models.Model): freguesia = models.ForeignKey(Freguesia, on_delete=models.CASCADE,verbose_name="Freguesia") rua = models.ForeignKey(Rua, on_delete=models.CASCADE,verbose_name="Rua") porta = models.PositiveIntegerField(verbose_name="Numero de polícia") tipo_avaria = models.ForeignKey(Tipo_avaria, on_delete=models.CASCADE,verbose_name="Tipos de avaria") class Pavimentacao(models.Model): avaria = models.ForeignKey(Avaria, related_name='AvariaObjects',on_delete=models.CASCADE) pavimento = models.ForeignKey(Pavimento, on_delete=models.CASCADE, verbose_name="Pavimento") class Pavimento(models.Model): nome = models.CharField("Pavimento",max_length=200) MY DEF (INSIDE OF AvariaAdmin) def Imprimir(self, request, obj): data = { 'obj':obj } pdf = render_to_pdf('daa/imprimir/avarias_pdf.html', data) if pdf : response = HttpResponse(pdf, content_type='application/pdf') filename ="Avaria_%s.pdf" %("123451231") content = "inline; filename='%s'" %(filename) response['Content-Disposition'] = content download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") MY HTML <table style="width:100%"> <tr> <th>ID:</th> <th>Freguesia:</th> <th>Rua:</th> <th>Porta:</th> <th>Tipo avaria:</th> <th>Pavimento:</th> </tr> {% for item in obj %} <tr> <td>{{item.id}}</td> <td>{{item.freguesia }}</td> <td>{{item.rua}}</td> <td>{{item.porta}} </td> <td>{{item.tipo_avaria}} </td> <td>{{item.pavimento}} </td> </tr> {% endfor %} </table> -
Don't overcome to call function inside another one
I'm working with django 1.11 and I would like to call a little function inside another one. The issue comes from parameter inside the called function. The function lets to get the email from the logged user : def get_user_email(request): user_email = request.user.email return user_email And the other one make some things, but I need to pick up the email : @shared_task(bind=True, time_limit=3600, soft_time_limit=3600) def get_xls_export(self, model="", search_info="", query_params=None, **kwargs): # Some things # Call the previous function user_email = get_user_email() Which attributes I have to write in my function in order to call it correctly ? Thank you -
Peer connection closure during request
I have a python app running behind Apache/WSGI that suffers from an annoying issue. One of the views dequeues a task from RabbitMQ, forms the HTTP response and returns it. The issue comes when a worker makes a client connection that is closed after reading the request but before forming the response. As a result, the task from the queue is permanently lost. At a loss for how to best manage this situation. Ideally the task could be returned to the queue if the connection loss could be detected but until the response is formed and returned by the handler, there is no way to know that the connection has been closed. Am I missing something obvious? def get_task(request): data = [] task = queues.dequeue() if task: data = task_to_json(task) return HttpResponse(json.dumps(data), content_type='application/json') -
Can I over ride multiple RegexURLResolver in django?
What is the best way to write multiple RegexURLResolver. I would like to create two urlpatterns one for language and another one for country. My requirement is to accept language patterns as /ar/user/2/detail/, /en/user/2/detail/ and country patterns as /usa/user/2/detail/, /saudi/user/2/detail -
Django allauth - disable connecting social account to existing account
User can signup either locally or by Google social signup. To avoid the middle form I've added: SOCIALACCOUNT_AUTO_SIGNUP = True which works except this case: User is registered manually with email "x@gmail.com". Then he decide to login using Google. In this case, the form is to be filled. I want to avoid this form at all. Is it possible? Either to return error if user is already registered manually Or connect the account automatically without the form I tried this adapter: class SocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): # social account already exists, so this is just a login if sociallogin.is_existing: return # some social logins don't have an email address if not sociallogin.email_addresses: return # find the first verified email that we get from this sociallogin verified_email = None for email in sociallogin.email_addresses: if email.verified: verified_email = email break # no verified emails found, nothing more to do if not verified_email: return # check if given email address already exists as a verified email on # an existing user's account try: existing_email = EmailAddress.objects.get(email__iexact=email.email, verified=True) except EmailAddress.DoesNotExist: return # if it does, connect this new social login to the existing user sociallogin.connect(request, existing_email.user) Which returns: builtins.TypeError TypeError: is_open_for_signup() missing 1 … -
How to write a neural network, for hand written text recognition, also how to pre process the IAM dataset for training
I am trying to build a neural network, which will recognise hand written texts , for that purpose , I am using the IAM hand written texts dataset, but not sure how to convert that data into trainable format, and also how to feed that in batches to the neural network. I decided to use 5 layers of CNN and 2 layers of RNN (lstm) But the image size is too large ( 1661 x 81) pixels, not sure if I have to downscale the image size. Also not sure how should I convert all that data into trainable format, I am using tensorflow and opencv for this purpose. Let's say, once the neural network is trained , then how to deploy that trained model into web app, and get the output for the inputs I provide. Can I use django and MySQL for this purpose?? If yes , then how?? -
Search ListAPIView in Django Rest API
I want to filter the list view using API View. But it is not filtering according to query. How can i do search query. Can ListAPIView method will be POST # Jobs API class JobsListAPIView(generics.ListAPIView): serializer_class = JobListSerialzer # pagination_class = ListLimitOffsetPagination permission_classes = [UserIsAuthenticated] def get_queryset(self, *args, **kwargs): # print('self.request.auth', self.request.auth.application.user.userprofile.user_company.id) qs = Jobs.objects.exclude(job_is_deleted = True).filter( job_company = self.request.auth.application.company ) query = self.request.data.get("query") print('query: ', query) if query: qs = qs.filter(job_status=query) return qs -
RESTful API: is it good to have foreign key which sends to different version of the API?
We are developing a RESTful API using Django REST framework, and we decided to handle foreign keys showing a URL to the relation's resource, for example: GET https://url_to_api/api/v2/foo/1: { "id": 1, "bar": "https://url_to_api/api/v2/bar/6/", "baz": "https://url_to_api/api/v3/baz/4/" } This is a GET request for the foo's ID 1 on the version 2 of the API. Django REST framework returns the URL to the v2 for the relation with the bar entity because /api/v2/bar/6/ sends to a view which is only used by this version, but it returns an URL to v3 (https://url_to_api/api/v3/baz/4/) for the relation with the baz entity, because its view is the same as the v2's one, and Django REST framework reverse engine returns the first result for the URL which sends to the same view. I have a couple of questions about this behaviour: is it a normal behaviour or we are missing or doing something wrong? is it good to have URLs which sends to a different version of the API? Any other ideas on how to manage this? -
Django application translation does not take effect
Page does not show msgstr but only msgid. I use python manage.py compilemessages.files are located between direcory locale -
Get latitude and longitude of the device
In my Django web application, i am trying to fetch the device(android tablet) current latitude and longitude using python. I can easily get the latitude and longitude using the device IP. ip_request = requests.get('https://get.geojs.io/v1/ip.json') my_ip = ip_request.json()['ip'] geo_request_url = 'https://get.geojs.io/v1/ip/geo/' + my_ip + '.json' geo_request = requests.get(geo_request_url) geo_data = geo_request.json() print(geo_data['latitude'], geo_data['longitude']) But somehow i am not getting the device exact IP. I am getting only the gateway address which is showing a different location. Is there any way to get my device exact IP or any way to get the latitude and longitude without using the device IP. Any help would be greatly appreciated. Thanks.. -
Convert pandas dataframe to html table
I am working on a django application. In the application I am trying to display a pandas dataframe in a django template. I am loading a csv file as follows. df = pd.read_csv(os.path.join(path, str(request.FILES['file']))) table_content = df.to_html() context = {'table_content': table_content} return render(request, 'index.html', context) The problem I am facing is when I try to display the table. In the template I am retrieving the dataframe as {{table_content}}. But this just displays the html code for the table and not the table itself. I can do a HttpResponse to display the table, but then the rest of the content in the template disappears and only the table is displayed. What am I doing wrong? -
Django - Open create/add form with fields precompiled based on other object model
In my project I use Django admin with Django 1.11, so I have a modelA and a modelB and users can create both of them, but sometimes I need to create a modelA object with some values field based on modelB object. To do this I have override my /templates/my_app_name/my_modelB/change_form.html template and add a button like this: {% extends "admin/change_form.html" %} {% load i18n admin_urls %} {% block object-tools-items %} <div class="form-row form-row-field-quick-view"> <a href="create_object_A_view">Create ObjA from this ObjB</a> </div> {% endif %} {% endblock %} In this way when I open some ObjB change form I get a link, based on a view whose task is redirect users to the url /admin/app_name/modelA/add/ and show the proper form with some fields precompiled based on ObjB values wich the form came from. So I created a view like this: class create_object_A_view(View): model = ModelA url = '/admin/app_name/modelA/add/' def get(self, request, *args, **kwargs): #get data from objB, say it foo and bar.... form = ModelAForm(initial={'field1': 'foo' , 'field2':'bar'}) return redirect(self.url, {'form':form, 'opts': self.model._meta, 'change': False, 'is_popup':False, 'save_as':False, 'has_delete_permission':False, 'has_add_permission': False, 'has_change_permission': False}) Doing this I get the correct redirect to /admin/app_name/modelA/add/ but the fields that I want to be precompiled are empty. … -
Method Not Allowed - Django Rest Framework
I am getting error while updating. When i add data it is added successfully. This error is only comming for UpdateAPIView { "detail": "Method \"POST\" not allowed." } urls.py path('groups/update/<int:pk>', views.GroupsUpdateAPIView.as_view(), name='api_groups_update'), Views.py class GroupsUpdateAPIView(generics.UpdateAPIView): queryset = Groups.objects.all() serializer_class = GroupsAddSerialzer permission_classes = [UserIsAuthenticated] def perform_update(self, serializer): serializer.save( group_updated_by = self.request.auth.application.user, ) Serializer.py class GroupsAddSerialzer(serializers.ModelSerializer): class Meta: model = Groups fields = ['group_name', 'group_description', 'group_status'] -
Additional field shows up outside table in admin change_list view
I have a model called Project in an app called projects that I registered with the admin site so the instances can be added/edited/etc. This works as expected. Now I want to add a button for each project in the change list view on the admin site, that links to a custom form that requires a Project instance to do things. I followed a bunch of different tutorials to customize the admin site and managed to add another field to the table of the change list view. However the entries show up outside the table (see image). I added the custom field by overwriting the admin/change_list.html template and calling a custom template tag custom_result_list within it. This tag adds a table field to the change list and then calls the admin/change_list_results.html template to render it. I have confirmed with a debugger that the item is added to the entries of the change list before the template is rendered (see image). I cannot explain why the table is not rendered correctly even though the additional field has the same structure as the auto-generated ones. I have to admit I have resorted to Cargo Cult Programming, because I do not understand how … -
Can i write code which explore data from API in models.py file
I am creating site which will extracting data from external API and store it in database than show it in front end. I was create models to store data in database now i didn't understand where i should write code which will extract data from API, can i write my exploring data from api code in models.py file or i should create code in another place. -
Django Rest Framework filter on the base of JSONField nested objects
I'm working on a Project using Python(3), Django(1.11) and DRF in which I have to filter the data on the base of a json object field which is saved as JSONFIELD in db model. Here's what I have tried: model.py: from django.db import models import jsonfield class MyModel(models.Model): id = models.CharField(primary_key=True, max_length=255) type = models.CharField(max_length=255) props = jsonfield.JSONField() repo = jsonfield.JSONField() created_at = models.DateTimeField() serializers.py: class MyModelSerializer(serializers.ModelSerializer): props = serializers.JSONField() repo = serializers.JSONField() class Meta: model = EventModel fields = "__all__" Json object: { "id":4633249595, "type":"PushEvent", "props":{ "id":4276597, "login":"iholloway", "avatar_url":"https://avatars.com/4276597" }, "repo":{ "id":269910, "name":"iholloway/aperiam-consectetur", "url":"https://github.com/iholloway/aperiam-consectetur" }, "created_at":"2016-04-18 00:13:31" } views.py: class PropsEvents(generics.RetrieveAPIView): serializer_class = MyModelSerializer def get_object(self): print(self.request.parser_context['kwargs']['id']) queryset = MyModel.objects.filter(data__props__id=self.request.parser_context['kwargs']['id']) obj = get_object_or_404(queryset) return obj It should return the MyModel records by props ID and should be able to return the JSON array of all the MyModel objects where the props ID by the GET request at /mymodel/props/<ID>. If the requested props does not exist then HTTP response code should be 404, otherwise, the response code should be 200. The JSON array should be sorted in ascending order by MyModel ID. When I sent a request to this view, it returns an error: django.core.exceptions.FieldError: Unsupported lookup 'id' for JSONField … -
KeyError in group by query in Django
I want group to paper_quality , paper_size and paper_brand fields which have common data and want to sum the balance sheets. I have tried all steps which I know like using custom serializer. class InwardDetails(models.Model): paper_quality = models.ForeignKey(PaperType, on_delete=models.PROTECT) paper_size = models.ForeignKey(PaperSize, on_delete=models.PROTECT) paper_brand = models.ForeignKey(PaperBrand, on_delete=models.PROTECT) thickness = models.CharField(max_length=100) reams = models.IntegerField() sheets = models.IntegerField() job_card = models.CharField(max_length=100) amount = models.IntegerField() cost_per_sheet = models.IntegerField() total_sheets = models.IntegerField() balance_sheets = models.IntegerField(default=0) account_access_key = models.ForeignKey(Ledger, null=True, blank=True, on_delete=models.PROTECT) serializer.py class class InventoryListSerializers(ModelSerializer): class Meta: model = InwardDetails fields = ['paper_quality', 'paper_size', 'paper_brand', 'balance_sheets', 'thickness'] views.py class GetListApiView(APIView): def get(self, request): queryset = InwardDetails.objects.values('paper_quality', 'paper_brand', 'paper_size').annotate(Sum('balance_sheets')) print(queryset) serializer = inward_inventory_serializers.InventoryListSerializers(queryset, many=True) return Response(serializer.data) -
Django creating a custom list_filter
I want to create a custom list_filter on AvariaAdmin, to check if env_emp is empty or not , i dont know how to do that My MODELS class Avaria(models.Model): ....... class Pavimentacao(models.Model): avaria = models.ForeignKey(Avaria, related_name='AvariaObjects',on_delete=models.CASCADE) env_emp= models.DateField(blank=True,null=True) ..... -
Django sperate migrations for seprate tenants with seperate apps,in same database
I am trying to make two tenants with separate apps and models, the migrate_schemas make migrations for all the apps so need to separate the migrations is it possible -
Pyhton is failing to build wheels for cassandra , cffi ,numpy etc on windows
On doing pip3 install requirements.txt I get this and exit Failed building wheel for pycrypto Running setup.py clean for pycrypto Failed to build cassandra-driver argon2-cffi cffi numpy pycrypto ERROR: Failed to build one or more wheels -
How to check if an object is within an array's objects values?
I'm building a server for Django Rest Framework. It models houses, contracts and owners. Basically, a House can have several Contracts and each Contract has an Owner. I'm writing a custom permission for a DetailViews for the Houses which should only allow the request, if you own the House (if you have a Contract for that House and you are the Owner. Here is what I have so far: class UserOwnsTheHouseSlugInUrlPermission(permissions.BasePermission): """ Permission to check if the user is an owner for the given House. This permission needs a house_slug to be given in the url. """ message = _(USER_IS_NOT_OWNER_PERMISSION_DENIED_MESSAGE) def has_object_permission(self, request, view, obj): owner = get_object_or_None(UserOwnerProfile, user=request.user) if owner and owner in obj.contracts.owner: return True return False This code does not work. In JavaScript you could write: if(obj.contracts.map(contract => contract.owner).includes(owner)) Or something similar. Python is not my main language, so I don't know how to express that condition in Python or Django. How would you go about writing this? Thank you very much 😊 -
How to get Api Body Parameter in Django
I want to get api body parameter in my view. I want to apply search filter. I am using self.request.GET.get('query') but it is alway giving none. How can i get Body Parameter Like from Postman i am sending query:Active in body. But i am not getting it class JobsListAPIView(generics.ListAPIView): serializer_class = JobListSerialzer # pagination_class = ListLimitOffsetPagination permission_classes = [UserIsAuthenticated] def get_queryset(self, *args, **kwargs): # print('self.request.auth', self.request.auth.application.user.userprofile.user_company.id) qs = Jobs.objects.exclude(job_is_deleted = True).filter( job_company = self.request.auth.application.company ) query = self.request.GET.get('query') print('query: ', request.data) if query: qs = qs.filter(job_status=query) return qs -
while submitting post from admin it gives me something like this Select a valid choice is not one of the available choices
I am trying to give posts category choices , everything works fine but if I add posts from admin panel I get error something like this Select a valid choice. SSC is not one of the available choices. this is my Posts/models.py from django.db import models from django.core.validators import FileExtensionValidator # Create your models here. CATEGORIES = ( ('SSC', 'SSCQUESTION'), ('CAT', 'CATQUESTION'), ) class Category(models.Model): title = models.CharField(max_length = 120, verbose_name="Title" ) updated_at = models.DateTimeField(auto_now_add=True, verbose_name="Updated at") created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Posts(models.Model): title = models.CharField(max_length=60) file_upload = models.FileField(null= True, blank=True, validators=[FileExtensionValidator(['pdf'])]) content = models.TextField() category = models.ForeignKey(Category, null= True,verbose_name="Category", on_delete=models.CASCADE,choices = CATEGORIES) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) # class Meta: # verbose_name = "Post" # verbose_name_plural = "Posts" # ordering = ['-created_at'] def __unicode__(self): return self.title def __str__(self): return self.title In admin panel this gives error like this -
How to deploy apps on herkou which use dlib?
I have been trying to deploy a Django web app to Heroku and I have dlib as a dependency. I have tried adding the build pack for which installs dlib and opencv. This is the buildpack that I have tried. But this does not work as this has become stale. I don't know if there is any other way to install dlib on Heroku? Here is the requirements.txt file for my app: dj-database-url==0.3.0 dj-static==0.0.6 gunicorn==19.7.1 Unipath==1.0 python-decouple==3 click==6.7 numpy==1.15.4 Pillow==5.2.0 face-recognition-models==0.3.0 cmake Werkzeug==0.14.1 face-recognition==1.2.3 boost==0.1 boost-py dlib==19.4.0 psycopg2==2.7.5 whitenoise==3.2 jsonschema==2.6.0 and this is the error that I get when I push to heroku master: Counting objects: 6, done. Delta compression using up to 4 threads. Compressing objects: 100% (6/6), done. Writing objects: 100% (6/6), 704 bytes | 0 bytes/s, done. Total 6 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing requirements with pip remote: Collecting Django==2.1.1 (from -r /tmp/build_6d2057dd8ed43f6db2772ce68b91cc1d/requirements.txt (line 1)) remote: Downloading https://files.pythonhosted.org/packages/ca/7e/fc068d164b32552ae3a8f8d5d0280c083f2e8d553e71ecacc21927564561/Django-2.1.1-py3-none-any.whl (7.3MB) remote: Collecting dj-database-url==0.3.0 (from -r /tmp/build_6d2057dd8ed43f6db2772ce68b91cc1d/requirements.txt (line 2)) remote: Downloading https://files.pythonhosted.org/packages/ef/b6/9283fcf61ced22bf90e7b4a84ba5b53d126b2c9b0dc9b667347698097026/dj_database_url-0.3.0-py2.py3-none-any.whl remote: Collecting dj-static==0.0.6 (from -r /tmp/build_6d2057dd8ed43f6db2772ce68b91cc1d/requirements.txt (line 3)) remote: Downloading https://files.pythonhosted.org/packages/2b/8f/77a4b8ec50c821193bf9682c7896f12fd0418eb3711a7d66796ede59c23b/dj-static-0.0.6.tar.gz remote: Collecting gunicorn==19.7.1 (from -r /tmp/build_6d2057dd8ed43f6db2772ce68b91cc1d/requirements.txt (line 4)) … -
NoReverseMatch at / Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[0-9]+)/like/$']
NoReverseMatch at / Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[0-9]+)/like/$'] I suspect there is some issue with my form but I'm unable to point out exactly whats wrong views.py from django.shortcuts import render,get_object_or_404 from django.views.generic import ListView from .models import Blog class BlogsList(ListView): model=Blog template_name='blog/home.html' context_object_name='blogs' ordering=['-date_posted'] def like_post(request, blog_id): post = get_object_or_404(Blog, id=blog_id) post.likes.add(request.user) return HttpResponseRedirect(Blog.get_absolute_url()) models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Blog(models.Model): title=models.CharField(max_length=100) content=models.TextField() date_posted=models.DateTimeField(default=timezone.now) author=models.ForeignKey(User, on_delete=models.CASCADE) likes=models.ManyToManyField(User,related_name='likes',blank=True) def __str__(self): return self.title urls.py from django.urls import path from . import views urlpatterns=[ path('',views.BlogsList.as_view(),name='blog-home'), path('<int:blog_id>/like/', views.like_post, name='like_post') ] html code {{ user.username }} {% block content %} {% for post in blogs %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <h2>{{ post.author }}</h2> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2>{{ post.title }}</h2> <p class="article-content">{{ post.content }}</p> </div> <div> <form action="{% url 'like_post' blog_id %}"> {% csrf_token %} <button type='submit' name='blog_id' value="{{ blog_id}}" class="btn btn-primary">Like</button> </form> </div> </article> {% endfor %} {% endblock %}