Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: extract time from datetime keeping the tzinfo?
In Django, how do extract the time of a datetime.datetime object keeping the tzinfo? In my code, I want a user to be able to edit the start time and end time of an object which contains start/end datetimes. That why I'm trying to create a form to edit the time part only: Forms class UpdateServiceForm(forms.ModelForm): class Meta: model = Service fields = tuple() start_time = forms.TimeField() end_time = forms.TimeField() Views class ServicesUpdateView(UpdateView): model = Service form_class = UpdateServiceForm def get_form(self, form_class=None): """ overrided to get start/end times from start/end datetimes """ form = super().get_form(form_class) form.fields['start_time'].initial = form.instance.start.time() form.fields['end_time'].initial = form.instance.end.time() return form It does not work because: form.instance.start returns an aware datetime (expected) form.instance.start.time() returns a naïve time. (I expected an aware time here. Of course, the bad hour is displayed in the form.) I browsed the django.utils.timezone section without finding the right tool. Any idea how to do this in a clean way? Thanks. -
How to run a custom aggregation on a queryset?
I have a model called LeaveEntry: class LeaveEntry(models.Model): date = models.DateField(auto_now=False, auto_now_add=False) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, limit_choices_to={'is_active': True}, unique_for_date='date' ) half_day = models.BooleanField(default=False) I get a set of LeaveEntries with the filter: LeaveEntry.objects.filter( leave_request=self.unapproved_leave ).count() I would like to get an aggregation called total days, so where a LeaveEntry has half_day=True then it is half a day so 0.5. What I was thinking based on the django aggregations docs was annotating the days like this: days = LeaveEntry.objects.annotate(days=<If this half_day is True: 0.5 else 1>) -
AttributeError: module 'json' has no attribute 'dumbs' [on hold]
I am tryin to create this flask app, but I receive this error AttributeError: module 'json' has no attribute 'dumbs' I checked most of the solutions which says there is a possible duplicate. I double checked but can't find any. my file name is recommender.py and other files in my directory nothing close to json I moved all my files to a new directory which only contains 3 files i'm using but still the same error. I created a virtual environment with my dependencies only, but still the same. Tried Python 2.7 and 3.5 I even removed the Json file from my python installation and downloaded it from the python directory on github, but still the same I even uploaded my code to a clean server, created a virtual env to test it again, but still I get the same error I tried running json.dumbs on another file and it works fine my_list = [ 'a', 'b', 'c'] my_json_string = json.dumps(my_list) those are my dependencies I am importing import pandas as pd import gensim.models.word2vec as w2v import codecs import itertools import regex import os import re import urllib from flask import Flask, url_for, Response, jsonify import json those are the … -
'AnonymousUser' object has no attribute '_meta' when trying to update user
In my app I am getting an error when trying to update a user info. my code is the following: def CandidateSignIn(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = MyUser.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) registered = False if request.method == "POST": form = TeamMembersFormUpdate(data=request.POST, instance=request.user) if form.is_valid(): user = form.save() user.set_password(user.password) user.save() #registered = True return HttpResponseRedirect(reverse('registration:HRlogin')) else: print("Error!") else: form = TeamMembersFormUpdate() return render(request,'candidateSignIn.html', {'form':form, 'registered':registered}) and apparently I am getting the error from the line form = TeamMembersFormUpdate(data=request.POST, instance=request.user) do you have any idea on how to solve this ? -
Django - Select related or join on two different base models
I have two base models SiteData and Showoroom Service that have model structure as per the below. I need the SiteData info but I also would like to get link_type from the showroomservice model if there is a matching ID. ive tried a few things thus far, none are getting what I need, what is the best way to achieve this? Thanks select related >>> nd = ShowroomService.objects.select_related('site').all() >>> nd Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 229, in __repr__ return '<%s %r>' % (self.__class__.__name__, data) File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 590, in __repr__ u = six.text_type(self) TypeError: __str__ returned non-string (type SiteData) Combining : >>> complete_data = site_data | monitoring_data Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 310, in __or__ combined.query.combine(other.query, sql.OR) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 529, in combine "Cannot combine queries on two different base models." AssertionError: Cannot combine queries on two different base models. chaining >>> final_data = chain(monitoring_data, site_data) >>> for i in final_data: ... '{} {}'.format(i.location,i.link_Type) ... Traceback (most recent call last): File "<console>", line 2, in <module> AttributeError: 'ShowroomService' object has no attribute 'location' sites.models.py class SiteData(models.Model): location = models.CharField(max_length=50) site_type = models.ForeignKey(SiteTypes, … -
Using Django Summernote without migration
Is there a way of using django-summernote without applying the migration? I am not using the attachment upload feature, so it's kinda useless for me to have a new table in my DB. I think that it should be parametrized along with the disable_upload option as it looks like uploading is the only reason for having a migration. -
Can I create virtual environment after installing Django?
I've already started using Django, but I didn't create a virtual environment before installing Django. -
Decoding Characters as printed in terminal
i am having a function that returns a json response in this format when printed in terminal [{"value": 17, "label": "PENDING_ENROUTE"}, {"value": 1, "label": "REJECTED_PREFIX_MISSING"}] but if i access the context variable holding the data in template it returns [{u&#39;value&#39;: 17, u&#39;label&#39;: u&#39;PENDING_ENROUTE&#39;}, {u&#39;value&#39;: 1, u&#39;label&#39;: u&#39;REJECTED_PREFIX_MISSING&#39;}] Anyone having an idea on how to resolve it, i have tried alot of ways but i couldn't find any solution. Somebody help. -
how can i show data one after another in django models
I am Using Django Framework in my project. I want the results that start with query first then results that contain query next but when I am using the following code it is giving mixed results instead of one after other. How can I achieve My requirement collections = TokenCollection.objects.filter(Q(title__istartswith=query) | Q(title__icontains=query)) -
getting TypeError: invalid file: <InMemoryUploadedFile: abc.json (application/octet-stream)> while uploading json file in django
class jsonUpload(CreateAPIView): serializer_class = UploadSerializer def post(self, request, *args, **kwargs): import json with open(request.FILES['file']) as data: d = json.loads(data) -
how to get url link on the response of get() method
I am trying to upload and get a response to an image using DRF api. the images are uploaded on the specified location but what i want is to get the link of the image so that i can click on it and could see the image when i get the response. if anyone could help me rectify this problem I would really be very thankful models.py file class employees(models.Model): name_of_employee = models.CharField(max_length=20, unique=True) name_of_department = models.CharField(max_length=20, unique=True) emp_id = models.IntegerField() image = models.ImageField(upload_to='Images/', default='Images/None/No-img.jpg') def __str__(self): return '{} {}' .format(self.name_of_employee, self.name_of_department) views.py file class employeeList(APIView): def get(self, request): employees1 = employees.objects.all() serializer = employeesSerializer(employees1, many=True) return Response(serializer.data) def post(self, request): serializer = employeesSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): employees1 = self.get_object(pk) employees1.delete() return Response(status=status.HTTP_204_NO_CONTENT) class employeeDetail(APIView): def get_object(self,pk): try: return employees.objects.get(pk=pk) except employees.DoesNotExist: raise Http404 def get(self, request,pk): employees1 = self.get_object(pk) employees1 = employeesSerializer(employees1) return Response(employees1.data) def put(self, request, pk): employees1 = self.get_object(pk) serializer = employeesSerializer(employees1, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_404_BAD_REQUEST) def delete(self, request, pk): employees1 = self.get_object(pk) employees1.delete() return Response(status=status.HTTP_204_NO_CONTENT) serializers.py file class employeesSerializer(serializers.ModelSerializer): image = serializers.ImageField(max_length=None, use_url=True) class Meta: model = employees fields = '__all__' … -
Docker - Django settings - Gunicorn ok but not manage.py
I read quite a few posts about this but still no solution... I have a docker-compose project with, among other, a django service that I build. On my prod environment, it is using gunicorn + nginx. All fine, working as expected. However on my dev environment, I am using only manage.py runserver. And here the troubles begin. Somehow, manage.py uses an old version of my settings.py that has been since then deleted. In my specific case, runserver is looking for a local mysql db, which doesnt exist because it is in another container. So, it is the same settings.py between gunicorn and manage.py, why does it work in one and not the other one??? My project structure: mysite |_ django_mysite/ | |_ __init__.py | |_ settings.py | |_ urls.py | |_ wsgi.py |_ myapp/ | |... |_ static/ | |... |_ manage.py |_ uwsgi_params My manage.py: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_mysite.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: … -
comparison with a key from django session
i setup a session key in django and tried to retrieve and compare with a string of the same elements, i have checked the type and they are all str but it cant return true otp = str(request.session["otp"]) print(otp,type(otp)) user_otp = str(request.POST.get("otp")) print(user_otp,"user_otp",type(user_otp)) if user_otp == request.session["otp"]: return HttpResponse("u enter") this is the log from the server after doing the print B3me <class 'str'> B3me user_otp <class 'str'> this shows they match but it doesnt return the HttpResponse -
How to test Graphql api which require user authentication
I am writing test for my application(Django+React.js+GraphQL) i have several api's which require a logged in user to access data. I am using django.contrib.auth for login/logout How can i write a simple test which can allow me to test some graphql api which require a logged in user. -
list index out of range issue, variables not existing yet
I am quite a beginner in python django and I am running through an issue that I guess I know how to solve but Iam not sure it is the right way to do it and I would like to have your point of view. My app is the following: A user create a project >> then create a team >> then invite member to the team >> is redirect to the project detail view The reverse is following the team member invitation. It is a questionnaire app so each invited members need to answer it and the answers is saved in "Response" and then I render the results in a dashboard. All my methods for the dashboard are in my views.py. My problem is that after inviting members all my methods are ran in the background but most of the variables do not exist yet since the invited user has not answered the questionnaire yet and I get an error like list index out of range is there a way to fix that without using an if/else/pass ? Method example : def get_current_team(self, format=None, *args, **kwargs): #import pdb; pdb.set_trace() current_team_member = Project.objects.get(id = self.kwargs['pk1']).team_id.members.all() members_response_list = [] for member … -
How to set the DestroyAPIView method not real delete my instance?
I have a model, like bellow: class BModel(models.Model): name = models.CharField(max_length=11) status = models.CharField(default="is_active") # if delete: deleted a = models.ForeignKey(AModel) def delete(self, using=None, keep_parents=False): pass # there I want to set the BModel's status to `deleted` Serializer: class BModelSerializer(ModelSerializer): class Meta: model = BModel fields = "__all__" Its Views is bellow: class BModelListAPIView(ListAPIView): serializer_class = BModelSerializer permission_classes = [] queryset = BModel.objects.all() class BModelDestroyAPIView(DestroyAPIView): serializer_class = BModelSerializer permission_classes = [] queryset = BModel.objects.all() My requirement is when use Django-Rest-Framework delete my BModel, I want to set the BModel's status field to deleted, not real delete the instance. How to access it? when I tried to write a delete method to my Model, there comes the default delete method: def delete(self, using=None, keep_parents=False): I have some questions about this: Is this is for the BModel's instance? Whether should through the delete method to access my requirement? -
how to access Item's database in the above code, so that I can create, update, or delete the items
class Hotel(models.Model): name = models.CharField(max_length=50) def get_absolute_url(self): return reverse('Hotel:detail', kwargs={'pk': self.pk}) def __str__(self): return self.name class Menu_time(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE,) period=models.CharField(max_length=50) def __str__(self): return self.period class Item(models.Model): period = models.ForeignKey(Menu_time, on_delete=models.CASCADE,) item=models.CharField(max_length=50) how to access Item's database in the above code, so that I can create, update, or delete the items -
django datefield is not store in MYSQL database correctly
I am using django and MYSQL. Below is my models.py: enter code here from django.db import models from django.utils import timezone import datetime from django.utils.translation import gettext as _ from bootstrap4_datetime.widgets import DateTimePicker from django import forms class Post(models.Model): WEEKDAYS=( ('Mon','Monday'), ('Tue','Tuesday'), ('Wed','Wednesday'), ('Thu','Thursday'), ('Fri','Friday'), ) TIMES=( ('morning','上午'), ('afternoon','下午'), ('night','晚上'), ) CUSTOMERS=( ('中兴','ZTE'), ('比特大陆','BITMAIN'), ('松果','PINECONE'), ('飞思卡尔','FREESCALE'), ('大唐','DATANG'), ) weekday = models.CharField(max_length=50,default='Mon',choices=WEEKDAYS) time = models.CharField(max_length=50,default='morning',choices=TIMES) customer = models.CharField(max_length=50,default='ZTE',choices=CUSTOMERS) pub_date = models.DateField(_("Date"), default=datetime.datetime.now().date) class Meta: ordering = ('-pub_date',) def __unicode__(self): return self.pub_date Here is database record: 13 2018-01-02 00:00:00.000000 中兴 morning Mon 14 2018-01-08 00:00:00.000000 中兴 morning Mon The database table shows the full time ,but I think datefield will only return format:YY-MM-DD。How to do to store date in YY-MM-DD format. Thanks! -
are routers in django Restframework necessary to use?
i have a stupid question about routers in DRF. so when i set url patters correctly and url endpoints are directing me to specific object.is this necessary to use routers?I am confused about this topic.better question: what is routers and why we should use it? -
django listbox add or remove dynamically into another listbox
i would like to create similar output as attached in question I have 3 models ModelA Stores all my master data ModelB Stores all my child data ModelC Should store master and child data based on my selection of pk(ModelA) and adding child data (ModelB) from listbox to another listbox. I have attached a image for your review. something similar i need Attached Reference -
django template url - add variable to string
Im trying to add a variable to the end of a string and am getting issues with reverse match, from what I gather the below should work {% for type in type_links %} <li><a href="{% url 'sites:site_list' 'all_'|add:type.id %}">{{ type.subnet_type }}</a></li> {% endfor %} I should have a url that has "all_1" for example in it. however I am getting a reverse url error Reverse for 'site_list' with arguments '('',)' not found. 1 pattern(s) tried: ['sites/site_list/(?P<display_filter>[\\w\\-]+)$'] is this correct way to add a variable to end the of the string? Thanks -
Transactions not working in Django using MySQL backend
I am regularily getting integrity errors for the following code snippet: class StatsManager(Manager): @transaction.atomic def create(self, **kwargs): kwargs.setdefault('date', date.today()) try: obj = self.get_queryset().get(**kwargs) except self.model.DoesNotExist: obj = super().create(hits=1, **kwargs) # line 28 else: obj.hits = F('hits') + 1 obj.save() return obj Here is the error message: IntegrityError at /emploi/cours-particuliers-en-physique-chimie-en-classe-de-superieur-1-evry-14skb.html (1062, "Duplicate entry 'EMP_VIEW-1903259-2018-01-08' for key 'statEvent'") And the traceback: File "/home/www/aladom_v6/www/stats/models/managers.py" in create 26. obj = self.get_queryset().get(**kwargs) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/django/db/models/query.py" in get 380. self.model._meta.object_name During handling of the above exception (Stats matching query does not exist.), another exception occurred: File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/django/db/backends/utils.py" in execute 65. return self.cursor.execute(sql, params) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/django_mysql/monkey_patches.py" in execute 35. return orig_execute(self, sql, args) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/django/db/backends/mysql/base.py" in execute 101. return self.cursor.execute(query, args) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/MySQLdb/cursors.py" in execute 250. self.errorhandler(self, exc, value) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/MySQLdb/connections.py" in defaulterrorhandler 50. raise errorvalue File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/MySQLdb/cursors.py" in execute 247. res = self._query(query) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/MySQLdb/cursors.py" in _query 411. rowcount = self._do_query(q) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/MySQLdb/cursors.py" in _do_query 374. db.query(q) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/MySQLdb/connections.py" in query 277. _mysql.connection.query(self, query) The above exception ((1062, "Duplicate entry 'EMP_VIEW-1903259-2018-01-08' for key 'statEvent'")) was the direct cause of the following exception: File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/channels/handler.py" in process_exception_by_middleware 243. return super(AsgiHandler, self).process_exception_by_middleware(exception, … -
Celery Task call continuassly run for minutes until the server is stop manually
The celery task call is running for minuteness (load server) I have to force stop the server. I change the Structure of Django Layout: config - settings - local.py - base. by celery.py urls.py apps -app_setA -app1 -app_setB -app1 -app2 -app_not In celery.py: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') app = Celery('TP') app.autodiscover_tasks() in setting.local CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Celery worker call(on windows): celery -A config worker -l info -P eventlet Call celery task: task_comp.delay(path) Task in tasks.py @task(name=task_comp) def task_comp.delay(path) print('inside task') -
getting error on installing package pyldap-2.4.45 on pypy3 environment
cc -pthread -shared build/temp.linux-x86_64-3.5/Modules/LDAPObject.o build/temp.linux-x86_64-3.5/Modules/ldapcontrol.o build/temp.linux-x86_64-3.5/Modules/common.o build/temp.linux-x86_64-3.5/Modules/constants.o build/temp.linux-x86_64-3.5/Modules/errors.o build/temp.linux-x86_64-3.5/Modules/functions.o build/temp.linux-x86_64-3.5/Modules/schema.o build/temp.linux-x86_64-3.5/Modules/ldapmodule.o build/temp.linux-x86_64-3.5/Modules/message.o build/temp.linux-x86_64-3.5/Modules/version.o build/temp.linux-x86_64-3.5/Modules/options.o build/temp.linux-x86_64-3.5/Modules/berval.o -L/usr/lib -L/usr/lib64 -L/usr/local/lib -L/usr/local/lib64 -R/usr/lib -R/usr/lib64 -R/usr/local/lib -R/usr/local/lib64 -lldap_r -o build/lib.linux-x86_64-3.5/_ldap.pypy3-510-x86_64-linux-gnu.so cc: error: unrecognized command line option ‘-R’ cc: error: unrecognized command line option ‘-R’ cc: error: unrecognized command line option ‘-R’ cc: error: unrecognized command line option ‘-R’ error: command 'cc' failed with exit status 1 ---------------------------------------- Command "/home/synerg-root/SAFE_V2/my-safe-pypy-env/bin/pypy3 -u -c "import setuptools, tokenize;file='/tmp/pip-iqwhlb2g-build/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-z13bd00v-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/synerg-root/SAFE_V2/my-safe-pypy-env/include/site/python3.5/pyldap" failed with error code 1 in /tmp/pip-iqwhlb2g-build/ -
How to create Dependent dropdown in Django forms?
I want to create dependent dropdowns. For example, if someone selects book from the first dropdown, second dropdown should have chapter listed under that book. I have achieved it using HTML / Jquery / AJAX. But i am now interested to achieve same using Django forms. If anyone have idea, please share it. Thank you in advance.