Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the requested user id from slack workspace via a python app?
I`m creating a slack application. This application creates a separate channel and puts some links inside this channel to view some web pages. Those web pages created from this app. Slack workspace members can click those links and view the web pages. Currently, these pages can access anyone. I want to give access to view web pages only for the slack workspace members. How can I do this? I am going to authorize users by the following logic Get all the workspace members from the slack API. Get the user id of the link clicked user. (How can I do this?) Then check whether is that user in the slack workspace. -
Django Rest Framework: MultipleObjectsReturned
It´s a requirement of the project to start from an existing database. In which there are tables with compound keys. When generating the models from this database, a field was left as the primary key, and a constraint unique with both fields that previously formed the composite key. An example follows: models.py class Preciosventalista(models.Model): idlistaprecio = models.OneToOneField(Listasprecios, models.DO_NOTHING, db_column='idlistaprecio', primary_key=True) idarticu = models.ForeignKey(Articulos, models.DO_NOTHING, db_column='idarticu') porcendescue = models.DecimalField(max_digits=6, decimal_places=2) cohefi = models.DecimalField(max_digits=10, decimal_places=4) precioneto = models.DecimalField(max_digits=10, decimal_places=4) precioventa = models.DecimalField(max_digits=10, decimal_places=2) class Meta: managed = True db_table = 'preciosventalista' unique_together = (('idlistaprecio', 'idarticu'),) serializers.py class ArticulosSerializer(serializers.ModelSerializer): class Meta: model = Articulos fields='__all__' class PreciosVentaListaSerializer(serializers.ModelSerializer): articulo = ArticulosSerializer(source='idarticu', read_only=True) class Meta: model = Preciosventalista fields='__all__' apiviews.py class PreciosVentaListaList(generics.ListCreateAPIView): queryset = Preciosventalista.objects.all() serializer_class = PreciosVentaListaSerializer class PreciosVentaListaDetalle(generics.RetrieveDestroyAPIView): queryset = Preciosventalista.objects.all() serializer_class = PreciosVentaListaSerializer urls.py urlpatterns = [ path('v1/preciosventalista/', PreciosVentaListaList.as_view(), name='preciosventalista_list'), path('v1/preciosventalista/<int:pk>', PreciosVentaListaDetalle.as_view(), name='preciosventalista_detalle') ] The error when calling the service ( /api/v1/preciosventalista/1 ) from postman is: MultipleObjectsReturned at /api/v1/preciosventalista/1 get() returned more than one Preciosventalista -- it returned 75! I couldn´t get my service to return a set of instances or to be able to filter through both fields (idlistaprice, idarticu) to return a single instance. I have tried the following without … -
wkhtmltopdf - Exit with code 1 due to network error: ContentNotFoundError
I am trying to build a PDF file out of the HTML file. When I run the command to convert the HTML file the response was Counting pages (2/6) Resolving links (4/6) Loading headers and footers (5/6) Printing pages (6/6) Done Exit with code 1 due to network error: ContentNotFoundError -
Running both websocket client and server using django
I'm trying to create a Django project that will consume data from an external websocket (django as a websocket client) and when there is update from this external websocket (onMessage()) I will want to publish this data out as a websocket server (using Channels). My question is: Where could I place the websocket-client code within a Django project? Do I need to use like Celery to run the websocket-client as a async task? Kindly please help and point me to a good direction, thanks. -
Error importing devserver module devserver.modules.sql: "cannot import name util"
Just upgraded from django 1.8 to 1.9 and getting this error while migrating: Error importing devserver module devserver.modules.sql: "cannot import name util" Although they say it is fixed it here: https://github.com/dcramer/django-devserver/issues/131 [localhost] local: python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/halit/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/home/halit/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 324, in execute django.setup() File "/home/halit/project_folder/.venv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/halit/project_folder/.venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/halit/project_folder/.venv/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/halit/project_folder./venv/local/lib/python2.7/site-packages/devserver/models.py", line 40, in <module> load_modules() File "/home/halit/project_folder/.venv/local/lib/python2.7/site-packages/devserver/models.py", line 25, in load_modules raise exceptions.ImproperlyConfigured, 'Error importing devserver module %s: "%s"' % (name, e) django.core.exceptions.ImproperlyConfigured: Error importing devserver module devserver.modules.sql: "cannot import name util" Fatal error: local() encountered an error (return code 1) while executing 'python manage.py migrate' Aborting. -
JQuery: Retrieve the input value by its name, which is within a div with an id
I'm trying to get the input value as the user types into the text field, using the div's id="search" and the name="vehicle" within the div. What I have currently done returns search_text as an empty string. I've simplified the code into help prove my issue: HTML <div id="search"> <input type="text" name="vehicle"> </div> JQUERY $(document).ready( function(){ $('#search').keyup(function() { $.ajax({ type: "POST", url: "http://localhost:8000/overview", data: { 'search_text': $('#search).Children("input[name=vehicle]") }, success: searchSuccess, dataType: 'html' }); }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search-results').html(data); } I've tried the following: 'search_text': $('#search input") and 'search_text': $('#search).Children("input[name=vehicle]") Thanks -
ValueError at /register: The given username must be set
ValueError at /register/ The given username must be set Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 1.11.4 Exception Type: ValueError Exception Value: The given username must be set here's the views.py def register_page(request): form = RegisterForm(request.POST or None) context = { "form": form } if form.is_valid(): print(form.cleaned_data) username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = User.objects.create_user(username,email,password) print(username) return render(request, "auth/register.html", context) This is sending None as a username and i dont know why? user = User.objects.create_user(username,email,password) How to resolve this issue? It is not getting the username with POST method or there is some other mistake? -
Python3/Django. Separate project directory from environment directory
Is it possible to have django projects(python3) directory outside of the environment directory? e.g I want to have my projects under /Users/me/Documents/dev/myDjangoProject and environment under /Users/me/Documents/env/myCustomEnvironment and somehow link them together. Thanks in advance -
Deploy different version of django application in same server
I'm using Apache & mod_wsgi to deploy a django application on my server. I am using Daemon mode of wsgi for running django application on server. Now my goal is that I can have two or more version of my django application on the same server (with each its own settings, databases, etc). For example: https://test-server.com/ https://test-server.com/dev I have updated apache configuration file located at /etc/apache2/sites-available. Here is my config file:- <IfModule mod_ssl.c> <VirtualHost *:443> ServerAdmin xyz@gmail.com ServerName test-server.com ServerAlias www.test-server.com #DocumentRoot /var/www/html Alias /static /var/www/html/Smart_chat_share/smart_chat_share/static // This should accesible via https://test-server.com/ which is working <Directory /var/www/html/Smart_chat_share/smart_chat_share/static> Require all granted </Directory> WSGIDaemonProcess smart_chat_share python-home=/var/www/html/Smart_chat_share/smart_chat_share/virtual_env python-path=/var/www/html/Smart_chat_share/smart_chat_share WSGIProcessGroup smart_chat_share WSGIScriptAlias / /var/www/html/Smart_chat_share/smart_chat_share/smart_chat_share/wsgi.py process-group=smart_chat_share application-group=%{GLOBAL} <Directory /var/www/html/Smart_chat_share/smart_chat_share/smart_chat_share> <Files wsgi.py> Require all granted </Files> </Directory> Alias /dev/static /var/www/html/dev/smart_chat_share/static // This should accesible via https://test-server.com/dev which is not working. <Directory /var/www/html/dev/smart_chat_share/static> Require all granted </Directory> WSGIDaemonProcess dev python-home=/var/www/html/dev/smart_chat_share/virtual_env python-path=/var/www/html/dev/smart_chat_share WSGIProcessGroup dev WSGIScriptAlias /dev /var/www/html/dev/smart_chat_share/smart_chat_share/wsgi.py process-group=smart_chat_share application-group=%{GLOBAL} <Directory /var/www/html/dev/smart_chat_share/smart_chat_share> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLCertificateFile /etc/letsencrypt/live/scss.identixweb.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/scss.identixweb.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> </IfModule> https://test-server.com/ this is working version but https://test-server.com/dev this second version i am not able to access and test.I'm often lost when it comes to Apache configuration. Your … -
Django is loading fixtures from different app
Let's say my Django project has two apps, foo and bar and both the apps have fixtures in it with the same file name for fixtures for eg: user.json, client.json etc. When I am running the test for app foo like: ./manage.py test foo How come the fixtures from bar: bar/fixtures is being loaded for the test run only for foo? -
extract manytomany field from a queryset
Models.py class AllotmentDocket(models.Model): sales_order = models.ForeignKey(MaterialRequest, on_delete=models.CASCADE, related_name='allotment_sales') class MaterialRequest(models.Model): kit = models.ForeignKey(Kit, on_delete=models.CASCADE, related_name='kit') quantity = models.IntegerField(default=0) class Kit(models.Model): kit_name = models.CharField(max_length=255, default=0) components_per_kit = models.IntegerField(default=0) product = models.ManyToManyField(Product, related_name='kit_product') How can I get all the products information through the related AllotmentDocket? I tried : def PrintAllotmentDocket(request, pk): AlotmentDocket = get_object_or_404(AllotmentDocket, id=pk) kit = MaterialRequest.objects.filter(id=AlotmentDocket.sales_order).values('kit') but this gives an error: int() argument must be a string, a bytes-like object or a number, not 'MaterialRequest' -
Rest uniform interface for calculator app
I am designing the rest api's for a basic calculator. I need to know which is the best practise for defining interfaces? /calc-service/add /calc-service/sub /cal-service/mul 2nd method /calc-service/?params -
Django: Query set to get AVG doesn't work
Currently, I try to get the average of all the answers to a specific question in my database. To achieve that I wrote the following query set. The answers are all numeric, but there still seems to be a problem with my query set. I receive the following error message function avg(text) does not exist LINE 1: SELECT AVG("surveys_answer"."answer") AS "avg" FROM "surveys... answers = Question.objects.filter( focus=QuestionFocus.AGE, survey__event=self.request.event, survey__template=settings.SURVEY_POST_EVENT, ).aggregate(avg=Avg('answers__answer')) models.py class Question(TimeStampedModel): survey = models.ForeignKey([...]) question_set = models.ForeignKey([...]) title = models.CharField([...]) help_text = models.TextField([...]) type = models.CharField([...]) focus = models.CharField([...]) required = models.BooleanField([...]) position = models.PositiveSmallIntegerField([...]) class Answer(TimeStampedModel): question = models.ForeignKey(related_name='answers') response = models.ForeignKey([...]) answer = models.TextField([...]) choices = models.ManyToManyField([...]) -
Django: Hiding the empty radio button option but still allowing it not to be null
I have a large model that I use over multiple pages. I made each page a separate form in my forms.py file. On some of the later form pages I include radio buttons. Based on what I've seen around Google, the only way to hide the empty radio button option is to make the radio button list required. In my case I did this the following way in my model: enlistment_date_known = models.CharField(max_length=10, choices=BOOL_CHOICES, blank=False, default=None) The problem is that these radio buttons are on my fourth page of my form, so when I submit the first page of my form, I get the following error: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot insert the value NULL into column 'enlistment_date_known', table 'LSPIntake_lonesoldier'; column does not allow nulls. INSERT fails. (515) (SQLExecDirectW); [23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The statement has been terminated. (3621)") Is there a way to allow the value of my radio buttons to be null in the database but still hide the first, blank option? Maybe by making the radio buttons required in the form instead of the model? -
I want to learn python Development. From where i can learn it easily? [on hold]
I want to learn python development with Django framework, From where i can learn it easily? I have some basic concepts of python -
Why list elements after space disappear when passed from views to Django template?
I use Django 2.1. I have some code in views.py: views.py ... zipped = zip(ph, mean) return render(request,'project/list.html', {'section': 'project', 'lines': zipped}) so far everything is correct, I debugged and all works. Data ph = ['Pre formation', 'Nice view'] #as an example not exact values mean = [10.0, 14.6] However inside html html {% for ph, mean in lines %} ... <td><input type="text" size="35" name="txt1" value={{ph}}></td> <td><input type="text" size="35" name="txt2" value={{mean}}></td> ... {% endfor %} Data I get Pre 10.0 Nice 14.6 Question: Why does it take only the text till space inside html? Inside views I debugged zipped has all information. How can I fix it? -
Decode JSON data before sending in API
I have created an API for a DB table. There is a field of 'day' which saves day in json formate like {"week1":["day1", "day2"], "week2":["day1", "day2"]} ({"1": ["3", "4"], "2": ["1", "2", "3"]}) Everything's working fine but I checked API on Postman, day is showing like this: "day": "{\"1\": [\"3\", \"4\"], \"2\": [\"1\", \"2\", \"3\"]}" when I checked Django admin, data is saving correctly in DB. Does any know how can I send decoded JSON data for this field? Here is my code: serializer.py class PlanToPackageSerializer(serializers.ModelSerializer): class Meta: model = PlanAllocationPackage fields = ('plan', 'day') depth = 1 class PackageListSerializer(serializers.ModelSerializer): package_name = PlanToPackageSerializer(many=True) class Meta: model = Package fields = '__all__' depth = 1 views.py class AllPackageView(APIView): def get(self, request): package = Package.objects.all() serializer = PackageListSerializer(package, many=True) return Response(serializer.data) -
Django localisation path separator Windows (\) vs macOS (/)
We've been maintaining a Django website with a few Mac and Linux users (through GitHub), but now a Windows-only person joined the team. We've come to one annoying little difference concerning the creation of .po localisation files. So far, we've always had paths with forward slashes: #: core/templates/home.html:8, but the Windows user generates paths with backslashes: #: .\core\templates\home.html:8. This makes it much more difficult to spot changes, since 750+ lines change everytime, rather than only the new or changed text & translations. I tried myself on a Windows computer and have the same result. What can we do to unify this? Thanks! -
Get data from JsonResponse in django
I wanted to know how to get data from a JsonResponse in django. I made a JsonResponse that works like this def pfmdetail(rsid): snpid = parseSet(rsid) if not snpid: return HttpResponse(status=404) try: data = SnpsPfm.objects.values('start', 'strand', 'type', 'scoreref', 'scorealt', rsid=F('snpid__rsid'), pfm_name=F('pfmid__name')).filter(snpid=snpid[0]) except SnpsPfm.DoesNotExist: return HttpResponse(status=404) serializer = SnpsPfmSerializer(data, many=True) return JsonResponse(serializer.data, safe=False) and then I call directly the method like this def pfmTable(qset,detail): source = pfmdetail(detail) print(source) df = pd.read_json(source) but it gives me an error. I know it's wrong because with the print it returns the status of the response which is 200 so I suppose that the response is fine but how can I access the data inside the response? I tried import json to do json.load but with no success. I even tried the methods of QueryDict but stil I can't acess to the content I'm interested P.S. I know that data contains something because if i display the jsonresponse on the browser i can see the JSON -
How to check if submit name is there or not in self.client.post?
Here I am writing test for function delete_position but I got little problem here.I am getting AssertionError: 302 != 200 which is I think because I have not send delete_single name in client.post but it is defined in my views. How can I check if delete_single is in request.POST in my test_delete_position ? views.py def delete_position(request, pk): position = get_object_or_404(Position, pk=pk) if request.method == 'POST' and 'delete_single' in request.POST: position.delete() messages.success(request, '{} deleted.'.format(position.title)) return redirect('organization:view_positions') else: messages.error(request, 'Sorry.Invalid request.') tests.py class PositionTestCase(TestCase): def setUp(self): # create admin user for authentication self.admin = get_user_model().objects.create_superuser(username='admin', password='password@123',email='admin@admin.com') self.client = Client() self.position = Position.objects.create(title='Sr.Python Developer') def test_delete_position(self): self.client.login(username='admin', password='password@123') response = self.client.post(reverse('organization:delete_position', kwargs={'pk': self.position.pk})) print(response) self.assertEqual(response.status_code, 200) -
How to pass the data through button using unique id in a dynamic table
i am using django and bootstrap and i want to pass data through button and show that data on bootstrap popup modal and i want that in each loop x.bots data should be passed uniquely so that i can access bot title ,bot id using another loop at x.bots {% for x in data %} <td>{% if x.bots %}<a href="#myModal" class="btn btn-primary btn-sm" data-toggle="modal" data="x.bots"> Show Bots &nbsp;{{ x.bots|length }}{% endif %}</a></td> {% endfor %} this is my script file <script> $(document).on('show.bs.modal','#myModal', function (event) { var button = $(event.relatedTarget); var recipient = button.data(x.bots); var modal = $(this); modal.find('.modal-title').text('Bots Title'); modal.find('.modal-body input').val(i); }) </script> but i tried alot using different ways but not getting the data -
How to show all total values in top not on every data
Here i am trying to get total values of all field and i got result but i want to show only one time all values not in every data so how to show this data in top only once "count": 6, "next": null, "previous": null, "results": [ { "pk": 1, "user": "Rahul Raj", "trwalk": 32, "Dtwalk": 13, "trclassic": 45, "Dtclassic": 16, "trelectric": 32, "Dtelectric": 12, "totalMilage": 122, "totalweight": 212, "phone": "372377233", "total_milage": 732, "total_weight": 1272, "total_travel_walk": 192, "total_distribute_walk": 78, "total_travel_classic": 270, "total_distribute_classic": 96, "total_travel_electric": 192, "total_distribute_electric": 72 }, But i want result like this "count": 6, "next": null, "previous": null, "total_milage": 732, "total_weight": 1272, "total_travel_walk": 192, "total_distribute_walk": 78, "total_travel_classic": 270, "total_distribute_classic": 96, "total_travel_electric": 192, "total_distribute_electric": 72 "results": [ { "pk": 1, "user": "Rahul Raj", "trwalk": 32, "Dtwalk": 13, "trclassic": 45, "Dtclassic": 16, "trelectric": 32, "Dtelectric": 12, "totalMilage": 122, "totalweight": 212, "phone": "372377233", }, and here is my code of serializers.py class UlectricSerializer(serializers.ModelSerializer): total_milage = serializers.SerializerMethodField() total_weight = serializers.SerializerMethodField() total_travel_walk = serializers.SerializerMethodField() total_distribute_walk = serializers.SerializerMethodField() total_travel_classic = serializers.SerializerMethodField() total_distribute_classic = serializers.SerializerMethodField() total_travel_electric = serializers.SerializerMethodField() total_distribute_electric= serializers.SerializerMethodField() class Meta: model = Muser fields = ('pk','user','trwalk','Dtwalk','trclassic','Dtclassic','trelectric','Dtelectric','totalMilage', 'totalweight','phone','total_milage','total_weight','total_travel_walk','total_distribute_walk', 'total_travel_classic','total_distribute_classic','total_travel_electric','total_distribute_electric') # Total Milage and Weight by Electric def get_total_milage(self, obj): totalpieces = Muser.objects.all().aggregate(total_milage=Sum('totalMilage')) return totalpieces["total_milage"] … -
Generating a Django Model that can have multiple values in one field
I am trying to generate a Django model that can handle multiple values in a single field. As such, when the first field is queried through a view, a user should select a value for the second view through a select box. To give a background of the problem, my seeding fixture looks like this... In the above scenario, location is the intended name of my model. Now, through a form, I want a user to be presented with 'countynames'. Upon selecting a countyname, the user should be presented with 'placenames' in the selected county for them to choose. I have tried the following format for the model... Now, I know that the error that is thrown, ('places' is not defined), is warranted. I was asking whether there is a way to define it (places), as it is in the fixture, or if anyone has a better implementation for such a model... any alternative way is welcome and appreciated as I can't think of anything at this point. -
How to use 'inspectdb_refactor' tool in django python?
I am trying to create models using postgresql, but it is giving me an error. I was using the following command. python manage.py inspectdb_refactor --database=garo2py --app=products I also added the inspectdb_refactor to my INSTALLED_APPS inside settings.py and also gave a database credentials as per following. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'garo2py', 'USER': 'projop', 'HOST':'localhost', 'PORT': '5432', } } I got the following error. Traceback (most recent call last): File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\utils.py", line 166, in ensure_defaults conn = self.databases[alias] KeyError: 'garo2py' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\inspectdb_refactor\management\commands\inspectdb_refactor.py", line 118, in handle self.handle_inspection(options) File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\inspectdb_refactor\management\commands\inspectdb_refactor.py", line 123, in handle_inspection connection = connections[options['database']] File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\utils.py", line 198, in __getitem__ self.ensure_defaults(alias) File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\utils.py", line 168, in ensure_defaults raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias) django.db.utils.ConnectionDoesNotExist: The connection garo2py doesn't exist -
Django-filter ForeignKey related Model filtering
I've been struggling with dajngo-filter recently. I have 2 models: Book and Author. class Book(models.Model): title = models.CharField(max_length=150) author = models.ForeignKey(Author, on_delete=model.CASCADE) length = models.PositiveIntegerField() class Author(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) year_of_birth = models.DateFiled() So, I'd like to make filter page, where you can find book by it's properties (title, author etc) AND information about author. For example book shorter than 300 pages, which author is beetween 20-25 years old. In filters.py I have: import django_filters from .models import Book, Author class BookFilter(django_filters.FilterSet): class Meta(): model = Book fields = ['title', 'author'] And have actually no idea how to also filter by different model, which is related by ForeignKey to Book model. I have really little experience with Dajngo, I wonder if it's very complex problem or not. :) Thanks!