Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django View not returning httpresponse
I have the following code to handle a simple form, my view is not sending back an http response. I can't figure out what's wrong with my code.. def novo_material(request): current_page='material' if request.method =='POST': form = SystemInventoryUpdate(request.POST) if form.is_valid(): name=form.cleaned_data['name'] qty=form.cleaned_data['qty'] unit=form.cleaned_data['unit'] t= NewMaterial(name=name,qty=qty,unit=unit) t.save() return HttpResponseRedirect(reverse('material')) else: form=NewMaterial() return render(request,'novo_material.html',{'form':form}) It is raising this error: The view dashboard.views.novo_material didn't return an HttpResponse object. It returned None instead. -
Count same field values in Django queryset
I have a Django model with three fields: product, condition and quantity with data such as: | Product | Condition | Quantity | +---------+-----------+----------+ | A | new | 2 | | A | new | 3 | | A | new | 4 | | A | old | 1 | | A | old | 2 | | B | new | 2 | | B | new | 3 | | B | new | 1 | | B | old | 4 | | B | old | 2 | I'd like to sum the quantities of the entries where product and condition are equal: | Product | Condition | Quantity | +---------+-----------+----------+ | A | new | 9 | | A | old | 3 | | B | new | 6 | | B | old | 6 | This answer helps to count entries with the same field value, but I need to count two fields. How could I implement this? -
Django rest-framework creating a view without model
I am pretty new to Django rest-framework and trying to render a simple JSON view not based on the model. I could not figure out how to do this since all of the examples involves rendering JSON from the Model classes. Below is the simple example what I was trying to do. class Comment(object): def __init__(self, email, content, created=None): self.email = email self.content = content self.created = created or datetime.now() def comment_view(request): comment = Comment(email='leila@example.com', content='foo bar') serializer = CommentSerializer(comment) json = JSONRenderer().render(serializer.data) return json -
dockerize gunicorn, nginx, django in single container
i am trying to dockerize my django project using gunicorn and nginx. The setup works on my machine, but i can't get nginx to work with the unix socket inside the image. i followed this tutorial. Since i can't use systemctl inside the container, i tried to run gunicorn as a CMD. To start Nginx, i tried restarting the container, but then my CMD is not restarted (i think?) and the container shuts down. How should i properly reload the nginx service inside the docker container using my dockerfile? -
Pandas dataframe to json for django
I want to load some initial data into my django app for a model, but it needs this specific format: [ { "model": "myapp.person", "pk": 1, "fields": { "first_name": "John", "last_name": "Lennon" } }, { "model": "myapp.person", "pk": 2, "fields": { "first_name": "Paul", "last_name": "McCartney" } } ] All the other ways I tried put square brackets or index values that I don't want. In the dataframe, the index will map to "pk" and the column values should be those in "field" ("first name" and "last name" would be the target columns of my dataframe). Using this code was the closest I got, but it adds square brackets around the values in "fields" df.groupby(['model', 'pk'], as_index=False) .apply(lambda x: {"first_name": df.first_name[x['pk']], "last_name": df.last_name[x['pk']]}) .reset_index().rename(columns={0:'fields'}) .to_json(orient='records') -
Arduino + Django Database
I would be so glad to you if you can help me. I was thinking about connect Arduino Uno to the Django Database. I would like to have a model in Database called Led. If there is value in Database 1 than the arduino turn on the led and in the čase there will be 0 the led will be off. Is it possible to connect arduino to the Django Database and recieve data ? Thank you so much for help. -
Retrieve values from Django Model and show in custom html
I am trying to retrieve values from my Model and display it in my template. I have custom HTML for CreateView and custom HTML for UpdateView. I have multiple radio buttons in my custom HTML in my update view. <div> <label class="control-label col-md-2">radio group1</label> <input type="radio" value="No Issue" name="group1" id="id_lens_dirty_0">No Issue <input type="radio" value="Non Critical" name="group1" id="id_lens_dirty_1"> Non Critical <input type="radio" value="Critical" name="group1" id="id_lens_dirty_2" > Critical </div> <div> <label class="control-label col-md-2">radio group</label> <input type="radio" value="No Issue" name="group2" id="id_lens_dirty_0">No Issue <input type="radio" value="Non Critical" name="group2" id="id_lens_dirty_1"> Non Critical <input type="radio" value="Critical" name="group2" id="id_lens_dirty_2" > Critical </div> <div> <label class="control-label col-md-2">radio group3</label> <input type="radio" value="No Issue" name="group3" id="id_lens_dirty_0">No Issue <input type="radio" value="Non Critical" name="group3" id="id_lens_dirty_1"> Non Critical <input type="radio" value="Critical" name="group3" id="id_lens_dirty_2" > Critical </div> <div> <label class="control-label col-md-2">radio group4</label> <input type="radio" value="No Issue" name="group4" id="id_lens_dirty_0">No Issue <input type="radio" value="Non Critical" name="group4" id="id_lens_dirty_1"> Non Critical <input type="radio" value="Critical" name="group4" id="id_lens_dirty_2" > Critical </div> <div> <label class="control-label col-md-2">radio group5</label> <input type="radio" value="No Issue" name="group5" id="id_lens_dirty_0">No Issue <input type="radio" value="Non Critical" name="group5" id="id_lens_dirty_1"> Non Critical <input type="radio" value="Critical" name="group5" id="id_lens_dirty_2" > Critical </div> Is there a way to get the values back and check appropriate radio button? I have about 50-60 radio button group … -
Viewing quires history in django
I need something to view the queries happened ( creating or updating or deleting ) in DB tables in Django, I want it to be able to be used by the user, not at the admin panel -
React Proxy error: Could not proxy request /api/ from localhost:3000 to http://localhost:8000 (ECONNREFUSED)
I have a React frontend that uses jwt to authenticate with the Django backend. The backend works and is connecting just fine using django views, but when I try to proxy a request from React, it gives me a Connection Refused error. Proxy error: Could not proxy request /api/auth/token/obtain/ from localhost:3000 to http://localhost:8000 (ECONNREFUSED). Connecting to http://localhost:8000/api/auth/token/obtain/ works normally. And sending a POST request with Axios also works normally and returns the token json. But when I proxy it with node, it doesn't work. In my package.json I have: "proxy": { "/api/*": { "target": "http://localhost:8000" } }, -
Django not finding static files inside Docker container
I have Django running inside a container, and I am unable to have it find static files. When I try and load /admin, I get a page with no css applied, and the error: Not Found: /my_app/admin/css/responsive.css My STATIC_URL and STATIC_ROOT look like: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = STATIC_ROOT = os.path.join(BASE_DIR, 'my_app/') STATIC_URL = '/my_app/' My directory structure inside the container looks like: / code/ my_app/ admin/ manage.py My DEBUG is set to True I know for a fact that the file exists: # (ls /code/ny_app/admin/css/responsive.css && echo yes) || echo no /code/my_app/admin/css/responsive.css yes When my container is started, I check for migrations that need to be made, as well as check for static collection: python manage.py migrate --noinput python manage.py collectstatic --noinput I have tried the suggestions from: Static Root and Static Url confusion in Django Django: CSS Is not not working Django not loading CSS? CSS is not working in Django app, no clue what is wrong All result in some form of Not Found -
How to setup Django settings.py with django-neomodel
I am new to stackoverflow, but i will try to ask my questions as clear as possible and do the same for any answers I will give. So here is my first question. I am currently learning Django and trying to connect it to neo4j's graph database. Here for I am using django-neomodel (https://github.com/neo4j-contrib/django-neomodel). However I can't seem to find where I put the following line in settings.py: NEOMODEL_NEO4J_BOLT_URL = os.environ.get('NEO4J_BOLT_URL', 'bolt://neo4j:test@localhost:7687') Can I just place this anywhere in the file? Thanks in advance! RickSancheez -
Unable to call multiple instances of sub tasks
I have a fairly simple celery/rabbitMQ/Django/docker application where I receive a request, spawn a task in queue1, and then within that task spawn X more tasks in queue2. Now the tasks in queue2 all try and perform some task, only one will succeed (and it will update some database within the task). My issue right now is that when I first submit a task to queue1 it will succeed, and I will see the proper results in the database. However I get the following message: rabbit_1 | =WARNING REPORT==== 30-Apr-2018::19:07:35 === rabbit_1 | closing AMQP connection <0.458.0> (172.19.0.1:40002 -> 172.19.0.2:5672): rabbit_1 | client unexpectedly closed TCP connection And on subsequent instantiations of tasks in queue1, I will see that both the task in queue1 and the tasks in queue2 complete, but I will not see the updated results in the database. I am guessing that there is a deadlock somewhere, or possibly something is wrong with my rabbitMQ set up. Here are the relevant bits: tasks.py @app.task def get_info(job_id, word): #grab output from some process and store as list output output = subprocess(...) jobs = group([long_t.s(l, word, job_id).set(queue="queue2") for l in output]) jobs.apply_async() @app.task def long_t(l, word, job_id): job = … -
How to enable pagination on DRF GenericAPIView?
So I recently switched over from using APIView to GenericAPIView - hoping this would give me access to more DRF features - pagination being one of them. My understanding was that I could just add this setting globally and pagination would just work on all GenericAPIViews settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 5 } This does not enable pagination. So then I also defined pagination_class as a class attribute class job(GenericAPIView): serializer_class = JobSerializer pagination_class = PageNumberPaginator def get_queryset(self): return Job.objects.all() def get(self, request, format=None): queryset = self.get_queryset() if queryset.exists(): serializer = JobSerializer(queryset, many=True) return Response(serializer.data) else: return Response({"Returned empty queryset"}, status=status.HTTP_404_NOT_FOUND) Still no pagination. This endpoint is returning over 100 records and adding string queries for ?page=1 or ?page=2 just returns the same 100+ list. What am I doing wrong here? I understand that I can just copy the DRF's paginator view methods inside my class - but I thought using GenericAPIView allowed me to easily leverage the built in pagination? -
Django d3.js load JSON data
I am trying to make a histogram with d3.js. I am new at javascript and JSON so I need your help. Basically I am trying to use this code here: How to make a bar chart for time duration with d3? The shown code here with the data in the code work fine, but how do I refer to my JSON outputted data? urls.py for my JSON data url(r'^api/playAround', views.playAround, name='playAround'), localhost/api/playAround [{"month": "2017-10-01", "countItems": 16}, {"month": "2018-04-01", "countItems": 1}, {"month": "2018-10-01", "countItems": 1}] How do I have to change the line var data =.... that I get my JSON data read and displayed? The line d3.json("{% url "playAround" %}", function(error, data) {} did not work. I think I do not get a main point in d3.js+JSON+javascript -
Python Django manage.py runserver too many values to unpack Passing a 3-tuple to include() is not supported
Trying to run python manage.py runserver on a virtual environment with a practically new django project but then getting this long error (venv) ugps-MacBook-4:mysite gust$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10d09b268> Traceback (most recent call last): File "/Users/gust/GoogleDrive/code/python/django/venv/lib/python3.6/site-packages/django/urls/conf.py", line 17, in include urlconf_module, app_name = arg ValueError: too many values to unpack (expected 2) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/gust/GoogleDrive/code/python/django/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/gust/GoogleDrive/code/python/django/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Users/gust/GoogleDrive/code/python/django/venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/gust/GoogleDrive/code/python/django/venv/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/gust/GoogleDrive/code/python/django/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/gust/GoogleDrive/code/python/django/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/gust/GoogleDrive/code/python/django/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Users/gust/GoogleDrive/code/python/django/venv/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/gust/GoogleDrive/code/python/django/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/gust/GoogleDrive/code/python/django/venv/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/gust/GoogleDrive/code/python/django/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/Users/gust/GoogleDrive/code/python/django/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, … -
Django: Why only change domain in email normalization?
In the BaseUserManager there is this method: @classmethod def normalize_email(cls, email): """ Normalize the email address by lowercasing the domain part of it. """ email = email or '' try: email_name, domain_part = email.strip().rsplit('@', 1) except ValueError: pass else: email = email_name + '@' + domain_part.lower() return email As far as I understand example@example.com is the same as eXaMPle@exAMPLE.CoM. Why does Django only change the domain part? -
unable to import pagseguro_urlpatterns from django_pagseguro.urls
I work with python 3 and install django-pagseguro. I tried to run command in python shell: from django_pagseguro.urls import pagseguro_urlpatterns and getting error: >>> from django_pagseguro.urls import pagseguro_urlpatterns Traceback (most recent call last): File "C:\Users\patff\AppData\Local\conda\conda\envs\k36\lib\site-packages\django_pagseguro\urls.py", line 3, in <module> from django.conf.urls import patterns, url ImportError: cannot import name 'patterns' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\patff\AppData\Local\conda\conda\envs\k36\lib\site-packages\django_pagseguro\urls.py", line 5, in <module> from django.conf.urls.defaults import patterns, url ModuleNotFoundError: No module named 'django.conf.urls.defaults' -
How to apply style to a Django form?
It is possible to change the style of form in the view? I found in documentation this code: <form action="/contact/" method="post"> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.subject.errors }} <label for="id_subject">Email subject:</label> {{ form.subject }} </div> <div class="fieldWrapper"> {{ form.message.errors }} <label for="id_message">Your message:</label> {{ form.message }} </div> <div class="fieldWrapper"> {{ form.sender.errors }} <label for="id_sender">Your email address:</label> {{ form.sender }} </div> <div class="fieldWrapper"> {{ form.cc_myself.errors }} <label for="id_cc_myself">CC yourself?</label> {{ form.cc_myself }} </div> <p><input type="submit" value="Send message" /></p> </form> But it just put a ugly input. I want to apply a class, or a css in this input. Is it possible? This is my form: class LoginView(NextUrlMixin, RequestFormAttachMixin, FormView): form_class = LoginForm success_url = '/' template_name = 'accounts/login.html' default_next = '/' class LoginForm(forms.Form): email = forms.EmailField(label='Email') password = forms.CharField(widget=forms.PasswordInput) -
Django ORM - LEFT OUTER JOIN with two columns?
This is the relevant code: class Book(models.Model): name = models.CharField(max_length=50) class BookNote(models.Model): text = models.CharField(max_length=50) book = models.ForeignKey(Book) user = models.ForeignKey(settings.AUTH_USER_MODEL) class Meta: unique_together = [('book', 'user'), ] Now, for a specific user in the website: I want to query all the books (all the table). And, For each book object, If the user has a BookNote for the book - get it, otherwise booknote should be null. This is how I would do that with SQL (works): SELECT book.name, booknote.text FROM book LEFT OUTER JOIN booknote ON (book.id = booknote.book_id AND booknote.user_id = {user_id_here}) This is what I've tried, does not work: qs = Book.objects.filter(Q(booknote__user_id=user_id_here) | Q(booknote__isnull=True)) I examine qs.query and I see why - Django uses WHERE clause to filter by user_id, so I don't get all the books. How can I do the same query with django ORM? Without raw sql? -
How can I access the json data that returned from JsonResponse in javascript, for updating the dom?
I made a django view that responses via JsonResponse(data), it perfectly response with json data when debugging, but I can't able to access these data in javascript for updating DOM. How can I access that json data? <script type="text/javascript"> $(document).ready(function(){ $('#{{ item.slug }}').click(function(){ $.ajax({ url: '/account/show_info/', data: {'owner_id':'{{ item.owner.id }}'}, datatype:'json', type:'GET', success: function(data){ $('.modal-title').html('{{ item.title }}'); $('.modal-body').html('{{ item.owner }}'); $('.modal-info').html(data.result); $('#myModal').modal('show'); }}); }); }); </script> *views.py def show_info(request): if request.method == 'GET': owner_id = request.GET['owner_id'] item = Profile.objects.get(user=owner_id) response = {} response['phone'] = item.phone response['location'] = item.location return JsonResponse(response) -
Django Rest Framework File Upload Api
Iam new to django.I need to upload a file using the Rest Framework API.Im looking to extract then list the metadata (package_name & package version code) from an android application(apk file). Basically something like this screenshot Here is my code so far. I can only do this through the admin, but i want it in such a way that when when file is uploaded,the serializer can get/extract the fields(package_name & package version code). models.py from django.db import models class Applist(models.Model): application = models.FileField(upload_to = 'uploads/') package_name = models.CharField(max_length=200) package_version_code = models.IntegerField(default=0) serializers.py import os from rest_framework import serializers from . import models class FileUploaderSerializer(serializers.ModelSerializer): class Meta: model = models.Applist fields = ('application', 'package_name', 'package_version_code',) def validate(self, validated_data): validated_data['name'] = os.path.splitext(validated_data['file'].name)[0] #other validation logic return validated_data def create(self, validated_data): return FileUploader.objects.create(**validated_data) views.py from rest_framework import viewsets from rest_framework.parsers import FormParser, MultiPartParser from . import models from . import serializers class FileUploaderViewSet(viewsets.ModelViewSet): serializer_class = serializers.FileUploaderSerializer parser_classes = (MultiPartParser, FormParser,) queryset = models.Applist.objects.all() def get_queryset(self, *args, **kwargs): qs = super(FileUploaderViewSet, self).get_queryset(*args, **kwargs) # qs = qs.filter(owner=self.request.user) return qs Not sure what do next -
What is the difference between SlugField() vs CharField() in Django models
So, in my Django projects, I made my model to be like the following class Store(models.Model): domainKey = models.CharField() I had the above to make each store has its own domain like the following www.domain.com/my-name-is-django Anyway, it was perfectly working fine. But, I just found out SlugField() which is used for the same purpose as what I did in above. My question is why we need to use SlugField() because I implemented the same thing without SlugField(). Is there its own any feature that CharField() doesn't have? -
Creating Django object in Javascript?
I have a Django model Sounds in models.py: class Sounds(models.Model): consonant = models.TextField(max_length=500, blank=True) vowel = models.TextField(max_length=500, blank=True) In views.py, I can create objects with: Sounds.objects.create(consonant="b", vowel="a") Obviously, I can't just do the same in a javascript file. Does anyone have any tips of what I could do instead? Thank you! -
Best platform for R based interactive websites?
Can Rshiny makes the website having similar features just like Django or php do? Like if I want to create users and an interactive real time website what should I choose in between Rshiny or Django? Also is angular.js compatible with the Rshiny apps? -
jwt.encode fails with "Object of type 'bytes' is not JSON serializable"
I am trying to return a token to my user after they have been successfully logged in but keep getting the following error: TypeError: Object of type 'bytes' is not JSON serializable How can I fix it? This is my code so far: if user: selected_user = { 'email': user.__dict__['email'], 'password': user.__dict__['password'], 'account_type': user.__dict__['account_type'], 'token': '' } if bcrypt.checkpw(request.data['password'].encode('utf8'), selected_user['password'].encode('utf8')): payload = { 'email': selected_user.email, 'account_type': selected_user.account_type } selected_user['token'] = jwt.encode(payload, "SECRET_KEY") response_details = { 'data': selected_user, 'message': 'Login successful.', 'code': '200', 'status': HTTP_200_OK } return Response(response_details, status=response_details['status']) else: response_details = { 'message': "Invalid password.", 'code': "400", 'status': HTTP_400_BAD_REQUEST } return Response(response_details, status=response_details['status']) else: response_details = { 'message': "Invalid email and password combination.", 'code': "400", 'status': HTTP_400_BAD_REQUEST } return Response(response_details, status=response_details['status'])