Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: 'encoding' is an invalid keyword argument for this function - How do I solve it?
I was trying to create an auto chatbot with bothub. It's a very new experience for me and I am stuck here I wish that I could find an answer here. JamesLees-MacBook-Pro:kakaotalkchatbot root# bothub logs Traceback (most recent call last): File "/usr/local/bin/bothub", line 11, in <module> sys.exit(main()) File "/Library/Python/2.7/site-packages/bothub_cli/main.py", line 539, in main cli() File "/Library/Python/2.7/site-packages/click/core.py", line 721, in __call__ return self.main(*args, **kwargs) File "/Library/Python/2.7/site-packages/click/core.py", line 697, in main rv = self.invoke(ctx) File "/Library/Python/2.7/site-packages/click/core.py", line 1065, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/Library/Python/2.7/site-packages/click/core.py", line 894, in invoke return ctx.invoke(self.callback, **ctx.params) File "/Library/Python/2.7/site-packages/click/core.py", line 535, in invoke return callback(*args, **kwargs) File "/Library/Python/2.7/site-packages/bothub_cli/main.py", line 497, in logs log_entries = lib_cli.logs() File "/Library/Python/2.7/site-packages/bothub_cli/lib.py", line 291, in logs self._load_auth() File "/Library/Python/2.7/site-packages/bothub_cli/lib.py", line 298, in _load_auth self.config.load() File "/Library/Python/2.7/site-packages/bothub_cli/config.py", line 46, in load with open(self.path, encoding='utf8') as fin: TypeError: 'encoding' is an invalid keyword argument for this function This is what I am getting and I cannot proceed from this TypeError: 'encoding' is an invalid keyword argument for this I would at least like to know what is the problem It's still okay if it's not solvable I would love to get suggestions with chatbot too Thanks. -
How to pass three or multiple arguments to custom template tag filter django?
How to send there arguments in @register.filter(name='thumbnail') template tag. I am using image resize function have contain 2 args image object and size now i want to pass third argument folder_name but i can't able to find the solution its gives error Could not parse the remainder: below are function which is template tag file and template. Template Tag function @register.filter(name='thumbnail') def thumbnail(file, size='200x200',folder_name='users_images'): x, y = [int(x) for x in size.split('x')] # defining the filename and the miniature filename filehead, filetail = os.path.split(file.path) basename, format = os.path.splitext(filetail) miniature = basename + '_' + size + format #filename = file.path #print(filehead+'/users_images/'+filetail) if os.path.exists(filehead+'/'+folder_name+'/'+filetail): filename = filehead+'/'+folder_name+'/'+filetail filehead = filehead+'/'+folder_name+'/' else: filename = file.path #print(filename) miniature_filename = os.path.join(filehead, miniature) filehead, filetail = os.path.split(file.url) miniature_url = filehead + '/' + miniature if os.path.exists( miniature_filename ) and os.path.getmtime(filename) > os.path.getmtime( miniature_filename ): os.unlink(miniature_filename) # if the image wasn't already resized, resize it if not os.path.exists(miniature_filename): image = Image.open(filename) new_image = image.resize([x, y], Image.ANTIALIAS) # image.thumbnail([x, y], Image.ANTIALIAS) try: # image.save(miniature_filename, image.format, quality=90, optimize=1) new_image.save(miniature_filename, image.format, quality=95, optimize=1) except: return miniature_url return miniature_url Template File I have tried 2 different type {{ contact_list.picture|thumbnail:'200x200' 'contacts'}} {{ contact_list.picture|thumbnail:'200x200','contacts'}} If any one have solution please help me. … -
Whenever null is forced into model's field, go to default string
I have a model like this: class Test(models.Model) name = models.CharField(max_length=30, default="Unassigned") Whenever this model's instance is being saved with None in the name field, I want the instance to be saved with "Unassigned" instead. But if I do this: >>> test = Test() >>>test.name = None >>>test.save() It will currently fail with django.db.utils.IntegrityError: NOT NULL constraint failed: explorer_api_test.name on the last line, because obviously the name field does not allow nulls (there is no null=True in it). But if I allow nulls, it will not save with default "Unassigned", but with None instead. How do I change the model definition so that whenever its instance is trying to be saved with None in the field, it is saved with default string instead? Outside of model definition, I could do this: >>>test = Test() >>>test.name = None >>>if test.name is None: >>>...test.name = "Unassigned" >>>test.save() but I prefer to have this logic in model itself. -
How does Django work with either instance id and instance itself?
For instance django queryset's filter takes either instance or instance_id. Probably django code needs id for Database query, and it extracts instance_id when it receives instance Although I don't remember, there could be a scenario where django would want instance but receives instance_id . How does django handle such cases? just do typechecking with isinstance(something, models.Model) and do something with it? -
Best approach to edit Mongo document from django POST API without exposing "_id"
I have a list of mongo documents at my UI, where at backend usually through "_id" I search and edit the respective document, But I want to know without exposing "_id" is there any better approach to edit it, because any one can forge by just increment the value of "_id" -
How to filter data from bokeh widget in Django
I'm having trouble getting the CustomJS to filter data in Django. Here I have two plots and one Select. I'm trying to get the select value to filter the data by name and display in the second plot. I'm not familiar with Javascript. This plots the first plot successfully but the select has no effect. Any help would be appreciated. names = ['Adam','Bella','Chaz','Duran','Eddy','Frank','Gallagher','Hen'] size=100 df2 = pd.DataFrame(data={ 'someone': np.random.choice(names, size=size, replace=True), 'metric': np.random.randint(0,10000, size=size), 'metric2': np.random.randint(0,10000, size=size), }) source2 = ColumnDataSource(df2) source3 = ColumnDataSource(data=dict(someone=[],metric=[],metric2=[])) plot = figure(plot_width=300, plot_height=300) plot.circle(x='metric', y='metric2', size=5, source=source2) plot2 = figure(plot_width=300, plot_height=300) plot2.circle(x='metric', y='metric2', size=5, source=source3) cb_testing = CustomJS(args=dict(s2=source2, s3=source3), code=""" var f = cb_obj.value; var d2 = s2.data; var d3 = s3.data; d3['someone'] = [] d3['metric'] = [] d3['metric2'] = [] for (var i = 0; i < d2['someone'].length; i++){ if (d2['someone'] == f){ d3['someone'].push(d2['someone'][i]) d3['metric'].push(d2['metric'][i]) d3['metric2'].push(d2['metric2'][i]) } } d3.change.emit(); """) selecttesting = Select(title="Select Name", options=names, callback=cb_testing) l4 = layout([ [selecttesting, plot, plot2] ]) script4, div4 = components(l4, ) -
Map home to django admin
I am using django 2.0.6 with apache2 and mod_wsgi. I would like to map the home url to admin of my application (an internal application which only has the admin and no public interface). The following code in url.py works when I am using django's runserver but does not work when I use apache2 with mod_wsgi urlpatterns = [ path('', admin.site.urls), ] When using apache2 with mod_wsgi, I get redirected to /cgi-bin/webproc saying "Not Found". The following works with both django's runserver as well as mod_wsgi urlpatterns = [ path('admin/', admin.site.urls), ] Would be grateful if anyone could help. -
In Django, how can I programmatically check that an IntegrityError is related to a particular uniqueness constraint of the model?
For example, if I have this model: # foo/models.py # Python standard library from uuid import uuid4 # Django from django.db import models class Foo(models.Model): uuid_1 = models.UUIDField(default=uuid4, unique=True) uuid_2 = models.UUIDField(default=uuid4, unique=True) And then I create instances of it: # Python standard library from uuid import uuid4 # Django from django.db import IntegrityError # foo app from foo.models import Foo const_uuid_1 = uuid4() const_uuid_2 = uuid4() first_foo = Foo.objects.create(uuid_1=const_uuid_1, uuid_2=const_uuid_2) # violate `uuid_1` uniqueness try: Foo.objects.create(uuid_1=const_uuid_1) except IntegrityError as e: pass # violate `uuid_2` uniqueness try: Foo.objects.create(uuid_2=const_uuid_2) except IntegrityError as e: pass So how can I tell the two uniqueness violations apart, programmatically? In my application, business requirements dictate that my program is allowed to automatically handle and correct one of the violations, but not the other (which must be reported back to the user). -
Reducing depth of json return by DRF
I have json API returned as below format. But I want to return json API decomposing namingzone key as specified below. Could anyone tell me how I can revise serializer to achieve this? serializer.py is also specified below. For models.py and views.py, please refer to my previous post. current { "zone": { "zone": "office_enclosed", "namingzone": [ { "naming": "moffice" } ] }, "lpd": 11.9, "sensor": true }, { "zone": { "zone": "office_open", "namingzone": [ { "naming": "off" }, { "naming": "office" } ] }, "lpd": 10.5, "sensor": true } Target { "zone": "office_enclosed", "naming": "moffice", "lpd": 11.9, "sensor": true }, { "zone": "office_open", "naming": "off", "lpd": 10.5, "sensor": true }, { "zone": "office_open", "naming": "office", "lpd": 10.5, "sensor": true } serializer.py class namingNewSerializer(serializers.ModelSerializer): class Meta: model=Naming fields=('naming',) class zoneSerializer(serializers.ModelSerializer): namingzone=namingNewSerializer(many=True) class Meta: model=Zone fields = ('zone','namingzone') class lightSerializer(serializers.ModelSerializer): zone = zoneSerializer() class Meta: model=Light fields = ('zone','lpd','sensor') class namingSerializer(serializers.ModelSerializer): zone=zoneSerializer() class Meta: model=Naming fields=('zone','naming') -
How can one return offloaded process response from celery?
I work on web application that generates pdf, it returns generated pdf file. Previously I handled the pdf generation in the main process. My superior told me, that will potentially cause the app to stall, as django is synchronous. So he suggest offload the process to celery, I tried it and have the idea about how to process it using celery. But I can't figure out the how to return the response to the client. I can return response that it's being processed, but what about the pdf file? return the possible url too? and send request every now and then? -
BASE_DIR outputs correct using print, but in a variable it just outputs C:
If im using print on base_dir = settings.BASE_DIR it outputs everything correctly. However when I use this variable to create a new variable using os.path.join, it just outputs C: Print example: C:\Users\me\Google Drive\gitlab\rootfolder Example on code where it just outputs C: and the paths after which shows up correct. blendfile = os.path.join(base_dir, '/var/media', userpathname, newest).replace("\\", "/") Comes out as: C:/var/media/userpathname/newest -
Django chatbot using Django channels
I am planning to create a simple "dialog trainer" using Django. I came across Django channels and noted that there are good resources available for django channels chat applications. I wish to know if there is a good resource which explains each step when developing a bot-server using Django as the back-end. The proposed chatbot has predefined set of questions and answers. I am going to populate the predefined questions/answers using a json file. If you know a good starting point where it explains, how to structure the project, reasoning for each step, please do share it here. Thanks -
How I can serialize information across 3 tables in DRF?
I have 3 tables(2 tables are belonging to 1 table using ForeignKey). I could create queryset across 3 tables. However, I cannot get naming table information from serialized return data as below. Could anyone tell me how I should revise serializer? views.py class lightData(generics.ListAPIView): serializer_class = lightSerializer pagination_class = None def get_queryset(self): certificate = self.kwargs['certificate'] return Light.objects.prefetch_related('zone__namingzone') models.py class Zone(models.Model): zone=models.CharField(max_length=20) conditioned=models.BooleanField(default=True) def __str__(self): return self.zone class Light(models.Model): zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='lightzone') lpd=models.IntegerField() sensor=models.BooleanField(default=True) class Meta: unique_together = (('certificate', 'zone'),) def __str__(self): return str(self.certificate)+"_"+str(self.zone) class Naming(models.Model): zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='namingzone') naming=models.CharField(max_length=20) def __str__(self): return str(self.zone)+"_"+self.naming serializer.py from rest_framework import serializers from .models import Certificate,Zone,Light,OA,Naming class zoneSerializer(serializers.ModelSerializer): class Meta: model=Zone fields = ('zone','conditioned') class lightSerializer(serializers.ModelSerializer): zone = zoneSerializer() class Meta: model=Light fields = ('zone','lpd','sensor') class namingSerializer(serializers.ModelSerializer): zone=zoneSerializer() class Meta: model=Naming fields=('zone','naming') -
Pass html file input, run python script on file, return file and string on webpage with django or flask
I have been doing some research and I can't seem to find what I am looking for. I wrote a python script using pandas to reformat an excel report. I would like to use the django or flask framework to build a simple site that allows the user to upload the file and then get the new one back all on the webpage. What is the best way to do this? -
Multiplying 2 Variables Together in Django
Hey so I'm looking to multiple (or add, any aggregation function really) the values of 2 django querysets together. I have tried this multiple ways and I am still running into a number of errors such as Request Method: GET Request URL: http://127.0.0.1:8000/paymentamount/ Django Version: 2.1.2 Exception Type: TypeError Exception Value: unsupported operand type(s) for *: 'QuerySet' and 'QuerySet' MODELS: class List(models.Model): vin = models.CharField(max_length=100, null=True, default=None) unit = models.CharField(max_length=10, null=True, default=None) year = models.CharField(max_length=4, null=True, default=None) make = models.CharField(max_length=100, null=True, default=None) model = models.CharField(max_length=100, null=True, default=None) trim = models.CharField(max_length=50, null=True, default=None) transmission = models.CharField(max_length=10, null=True, default=None) drivetrain = models.CharField(max_length=10, null=True, default=None) seats = models.IntegerField(default=0, null=False) kilometers = models.IntegerField(default=0, null=False) .... tier1book = models.FloatField(null=True, default=0) tierid = models.ManyToManyField('TDTier') class TDTier(models.Model): listid = models.ManyToManyField('List') bank = models.CharField(max_length=100, null=True, default=None) year = models.CharField(max_length=5, null=True, default=None) tier = models.CharField(max_length=100, null=True, default=None) frontendltv = models.FloatField(null=True, default=0) backendltv = models.FloatField(null=True, default=0) interest = models.FloatField(null=True, default=0) VIEWS: def payment(request): item = List.objects.all() item3 = List.objects.values_list('tier1book', flat=True) item6 = TD.objects.filter(list__year=F('year'), kmbottom__lte=F('list__kilometers'), kmtop__gte=F('list__kilometers')) item7 = TDTier.objects.filter(list__year=F('year'), tier=('5 Key')).values_list('frontendltv', flat=True) item8 = item3 * item7 return render(request, 'paymentamount.html', {'item8':item8) I get that trying to add 2 lists together does not work, however, Pythonic solutions do not seem to be … -
How to json response list of queryset from different models?
I have two models like this class User(models.Model): user_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=18) last_name = models.CharField(max_length=10) age = models.CharField(max_length=10) class Friend(models.Model): friend_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=18) age = models.CharField(max_length=10) friend_id and user_id is the same id's users = User.objects.filter(user_id=1) friends = Friend.objects.filter(friend_id=1) I make the union like this merge = list(users) + list(friends) [<User: User object (1)>, <Friend: Friend object (1)>] I want to do is a json response from merge HttpResponse(json.dumps(merge), content_type='application/json') I hope you understand my question and some idea of how to implement it -
Setup celery worker and celery beat (django app) on AWS ECS
I have a Django app with celery worker and beat, and I'm having a hard time trying to set up celery on ECS (The Django app was pretty straightforward). 1) What kind of service should I use for the worker and the beat: REPLICA or DAEMON? 2) What command could I use to the Healthcheck on the task definition configuration? I tried using supervisor and also simply calling the celery command directly in the command section of the task definition. I don't know what exactly I am missing... Supervisor configuration files: supervisor.conf: [unix_http_server] file=/var/run/supervisor.sock ; (the path to the socket file) chmod=0700 ; sockef file mode (default 0700) [supervisord] logfile=/var/log/supervisor/supervisord.log ; supervisord log file logfile_maxbytes=50MB ; maximum size of logfile before rotation logfile_backups=10 ; number of backed up logfiles loglevel=debug ; info, debug, warn, trace pidfile=/var/run/supervisord.pid ; pidfile location nodaemon=false ; run supervisord as a daemon minfds=1024 ; number of startup file descriptors minprocs=200 ; number of process descriptors user=root ; default user childlogdir=/var/log/supervisor/ ; where child log files will live [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL for a unix socket [include] files = /etc/supervisor/conf.d/*.conf celeryworker.conf: [program:celery] command=/start-worker.sh directory=/app user=myuser numprocs=1 stdout_logfile=/var/log/app_logs/celery-worker.log stderr_logfile=/var/log/app_logs/celery-worker.log autostart=true autorestart=true … -
How to access Meta on CustomNode using Graphene and Relay
I want to make a generic get_node_from_global_id, so I need to get the root model the query is requesting and then return a row from that table. To do this I want to use model = getattr(Query,info.field_name).field_type.Meta.model . The first part, getattr(Query,info.field_name).field_type gets me TableNameNode from Query using info.field_name. But when I try to access ...Meta.model I get an error saying that there is no attribute Meta on TableNameNode. I can see that there is a nested class Meta so how can I access it? from graphene_django import DjangoObjectType from graphene import relay class CustomNode(relay.Node): class Meta: name = 'Node' @staticmethod def to_global_id(type, id): #returns a non-encoded ID return id @staticmethod def get_node_from_global_id(info, global_id, only_type=None): user = info.context.user model = getattr(Query,info.field_name).field_type.Meta.model #return row here... pass class Query(object): tablename = CustomNode.Field(TableNameNode) class TableNameNode(DjangoObjectType): class Meta: model = TableName interfaces = (CustomNode,) -
how to get the file of an image? in python ? django rest framework
class DemoAPIView(APIView): parser_classes = (JSONParser, FormParser, MultiPartParser) def post(self, request, format=None): data = request.data attached_file = request.FILES['attached_file'] description_image = data.get('descriptionImage', None) attachment = dict(object_id=174, project=1, attached_file=attached_file, description=description_image) header = {'Authorization': 'Bearer eyJ1c2VyX2F1dGhlbnRpY2F0aW9uX2lkIjoxNn0:1gSTf6:KbOb0yhqC-qVPTEPRoiVBBZjN6M'} r = requests.post('demo/api/v1/issues/attachments', data=attachment, headers=header) print(r.json()) return Response({'error': 'ERROR XD'}, status=status.HTTP_400_BAD_REQUEST) and the error that the api booted me is the following: {'attached_file': ['No file was submitted. Check the encoding type on the form.']} which is the image that I sent from the client. print the attached file and just show me the url, apparently that's the problem. Is there any way to get the full file? -
Django manage.py runserver command freezing on OSX
I have a few different systems that I use for development of a Django project. The main being Linux, then Windows, and then Mac...all systems implement development using Pycharm Up until about a week ago I was able to develop my Django project on Mac just fine, I could run the server and check updates as usual, however, for some reason I cannot seem to figure out, the terminal just freezes for about 5 minutes when I run: python3 manage.py runserver 8000 The server still starts after that 5 minutes but the startup time is quite literally awful, and I do not know what to look at to figure out where the issue is. I have not changed my code between work and home, just pulled directly from Git and I have the same issues. On my Windows System at home the Django app also runs within a few seconds of starting the server, as does the Linux system at work, so it seems to be only happening on OSX. Again, I am using Pycharm, but even if I manually enter the project directory and run the server, the startup time is slow Has anybody run into issues like this, … -
saving blob in django creates a file with size 0
I post an audio blob to django using ajax, before posting I do console.log(blob) //prints //Blob(262188) {size: 262188, type: "audio/wav"} //size: 262188 //type: "audio/wav" //__proto__: Blob Inside the django view: from django.core.files.storage import default_storage from django.core.files.base import ContentFile audio_data = request.FILES.get("recordedBlob", None) print(type(audio_data)) #prints <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> print(audio_data.size) #prints 262188 path = default_storage.save('audio/' + '123' + '.wav', ContentFile(audio_data.read())) But when I open the audio file in my file system, it is size Zero Bytes. Any idea how to save the blob correctly? -
What does format=None do in Django rest full API
Recently when I read Django rest full API document I faced this code : def get(self, request, format=None): """Return a list of APIView features.""" an_apiview = [ 'Uses HTTP methods as function (get, post, patch, put, delete).', 'It is similar to a traditional Django view.', 'Gives you most control over you logic.', 'Its mapped manually to URLs.' ] return Response({'message': 'Hello!', 'an_apiview': an_apiview}) this code is work fine but I look for format=None and I cant find out what does it do. is any body know what is it and why its important to be? -
'NoneType' object has no attribute 'add'
I have the following User object, class User(AbstractBaseUser, PermissionsMixin, Base): username = models.CharField(db_index=True, null=False, unique=True, max_length=255) mobile = PhoneNumberField(db_index=True, null=False, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) And I've the following class to manage connections, class Connections(Base): owner = models.OneToOneField(User, on_delete=models.CASCADE, null=True) friends = models.ForeignKey(User, on_delete=models.CASCADE, related_name='friend_set', null=True, blank=True) followers = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower_set', null=True, blank=True) followings = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following_set', null=True, blank=True) When I try to add a friend, sender = User.objects.get(id=kwargs.get('sender_id')) receiver = User.objects.get(id=kwargs.get('receiver_id')) sender_connections, created = Connections.objects.get_or_create(owner=sender) sender_connections.friends.add(receiver) I get the following error, 'NoneType' object has no attribute 'add' Can someone help me with this? -
Django template variable does not show up
for some reason im unable to display the comments of a category_request and i have now idea why, is smb. maybe able to have an eye on that, praticaly i should work but i dont see the mistake here. as far as i see I'm using category_request_comment from the view to get a releated comment objects from a category_request... any idea? Template Snippet: {% for category_request_comment in category_request_comments %} <div class="comment"> <p>{{ category_request_comment.content|readmore:15 }}</p> {% if category_request_comment.content.published_date %} <div class="date"> <a>Comment by: {{ category_request_comment.author }}</a><br> <a>Commented at: {{ category_request_comment.published_date }}</a> </div> {% endif %} {% if request.user == category_request_comment.author %} <a class="commentoption" href="{% url 'comment_edit' pk=category_request_comment.pk %}">Edit</a><a> | </a> <a class="commentoption" href="{% url 'comment_delete' pk=category_request_comment.pk %}">Delete</a> {% endif %} </div> {% endfor %} views.py def category_request_detail(request, pk): category_request = get_object_or_404(CategoryRequests, pk=pk) list_category_request = CategoryRequests.objects.get_queryset().filter(id=pk).order_by('-pk') paginator = Paginator(list_category_request, 20) page = request.GET.get('page') category_request_comment = paginator.get_page(page) return render(request, 'myproject/category_request_detail.html', {'category_request': category_request, 'category_request_comment': category_request_comment}) views.py (only for Reference) def category_request_comment_new(request, pk): if request.method == "POST": form = CategoryRequestsCommentForm(request.POST) if form.is_valid(): category_request = get_object_or_404(CategoryRequests, pk=pk) requests_comment = form.save(commit=False) requests_comment.author = request.user requests_comment.published_date = timezone.now() requests_comment.category_request = category_request requests_comment.save() return redirect('category_request_detail', pk=requests_comment.category_request.pk) else: form = CategoryRequestsCommentForm() return render(request, 'myproject/comment_new.html', {'form': form}) urls.py url(r'^categories/requests/$', myproject_views.category_request_list, name='category_request_list'), … -
Why doesn't Django 2.1 login_required work when parameter is present
In urls.py I have: ... path('/admin/login', login_required(admin.site.login)) This reroutes to a custom authentication view, specified in settings.LOGIN_URL. When you go to /admin it redirects to /admin/login?next=/admin, which does not redirect to LOGIN_URL. But when you go to /admin/login directly, everything works correctly. Note: This worked correctly in Django 1.11.