Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Simplify Proxy Model to single class
I have User table in my DB, they can be active or inactive. If I only want to query on active user, I define a Proxy Model like following. class User(models.Model): name = models.CharField(max_length=50) location = models.CharField(max_length=50) active = models.BooleanField() class UserActive(models.Manager): def get_queryset(self): return super(UserActive, self).get_queryset().filter(active=True) class ActiveUser(User): objects = UserActive() class Meta: proxy = True Then by working with ActiveUser, I can do my calculation/statistic with only active user. The problem is, I need to define both UserActive and ActiveUser class, it seems awkward to me. Because with each main class (in this case is User), we need to define two other classes. Imaging we have several other model need to implement Proxy, the code would look messy. May I know if we can have more elegant way ? Thanks Alex -
Comparing two lists of dictionaries
I have a rather complex use-case where I need to compare two lists of dictionaries, however there are a variety of different states that the lists can be in and ideally I would like to be able to handle all of them in one. The background to this is that I have a form which is rendered as a table of checkboxes, and I am trying to get the difference between the initial data of the form and the cleaned_data being sent back when an update is made (i.e. checkboxes are checked or unchecked). So typically the initial data will contain only the data for checked checkboxes, e.g. initial_data = [<Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>] where an Event object contains a id and a name, they can be the same as it could be the same event. If a checkbox is unchecked then the cleaned_data might look like this: cleaned_data = [<Event: Event object>, None, <Event: Event object>, None] In this case I would like to get the events from the initial_data where there is None in the cleaned_data. The next use-case is that if checkbox is then checked the initial data may … -
After deploying to heroku
I have a webapp which is not yet complete but I recently deployed it to heroku. It uses: Django Rest-framework Reactjs Now, I have deployed deploy-heroku branch of my project to master of heroku. The only difference between my project's master branch and deploy-heroku branch is that I have made additional changes in settings.py (adding prostgre sql settings and all) in the deploy-heroku branch. I want to add more features to my webapp so should I work on master and later copy-paste those changes to deploy-heroku. This seems redundant !! Is there any other better way to do this? -
Root certificates are missing for certificate validation. Either pass them in using the ca_certs parameter or install certifi to use it automatically
I am using django-elasticsearch-dsl in one of our projects, and after creating a cluster in AWS Elasticsearch, I started seeing this error: Root certificates are missing for certificate validation. Either pass them in using the ca_certs parameter or install certifi to use it automatically.. There are some solutions proposed to solve the issue for https://elasticsearch-py.readthedocs.io in this linke [link][1], but that is not for django-elasticsearch-dsl which is using elasticsearch-py. I only can set the endpoint through the settings.py like this: ELASTICSEARCH_DSL = { 'default': { 'hosts': 'https://my-aws-elasticsearch-endpoint.eu-central-1.es.amazonaws.com' } } How can I add/enable this certificate for django-elasticsearch-dsl -
directory file import error in python
i am having file structure like /home/ec2-user/wep-rs/WEPR/weprs/api/voucher.py /home/ec2-user/wep-rs/WEPR/weprs/api/scrappers/quotes/quotes.py i want to access voucher.py from quotes.py i have tried these import sys sys.path.append("..")# ValueError: attempted relative import beyond top-level package from .. .. import api # ValueError: attempted relative import beyond top-level package sys.path.append("/home/ec2-user/wep-rs/WEPR/weprs/api/") from api.voucher import Voucher error i am getting is ModuleNotFoundError: No module named 'api' -
Dynamic forms with django
I am having an issue that I can't get around with, even though I tried a lot of solutions on SO and other sites, but they don't work for the dynamics I need (a lot is hard coded). The thing is, I have a file with a dictionary in it, which can be updated when more files are added to that "framework". It is a custom code project, that I am building a web interface for. So here is an example of that dictionary: filespatterns = { "file1": "Open File1", "file2": "Open File2", } Basically the same way Django works with the installed apps, you create the file with the classes and functions in it that you want it to work with. And through the web interface you can send commands to them. Now for the problem: I have Django set up that it reads that dictionary and creates a pulldown menu on the webinterface with no problem whatsoever, and I have no problem creating the forms for each of the interfaces based on the files. But considering the amount of forms needed is variable (and well, who would want a web interface with hundreds of forms stacked on top … -
use ajax to upload file in Django
I am going to add a button in my page to upload file.User clicks this button and choose file from computer, the page will upload file to the server and show a message like 'Upload successfully' to the user. I have noticed that Django has Filefield in model and we can define a class FileForm so that we can use form = UploadFileForm(request.POST, request.FILES) and form.save() to upload. However,as I want to refresh part of the page after upload, it comes to me to use ajax to send data.Furthermore,in order to use request.FILES which requires that request has the attribute enctype="multipart/form-data", I think maybe we can use FormData() in ajax. html: <div> <input type="file" name="" id="ul_input"> <input type="hidden" name="local_id" id="get-local-id" value="{{ record.local_id }}"/> </div> Javascript: // grab your file object from a file input $('#ul_input').change(function () { var formData = new FormData(); formData.append("ul_file", this.files[0]); formData.append("filename", this.files[0].name); formData.append("local_id", $('#get-local-id').val()); $.ajax({ url: 'uploadfile', type: 'POST', data: formData, processData: false, contentType: false, dataType: "json", beforeSend: function () { console.log("loading...please wait"); }, success: function (responseStr) { if (responseStr.status === 0) { alert('upload successfully'); } else { alert("upload fail"); } }, error: function (responseStr) { console.log("error"); } }); }); views.py def order_upload(request): status = 1 … -
real-time chat application based on websockets
I want to create one real-time chat application based on websockets. So in that clientside is angular5 and ServerSide is django. so, i am confused between two way to do this websocket. first is that do i have to set code of websocket in only python? second : Do i have to set code in both django and Angular? I tried second thing... model.py class User(models.Model): name = models.CharField(max_length= 20) def __str__(self): return self.name class Message(models.Model): time = models.DateTimeField(default=datetime.now) message = models.CharField(max_length=200) consumer.py def msg_consumer(message): text = message.content.get('text') Message.objects.create(message=text,) Group("chat").send({'text': text}) def ws_connect(message): Group("chat").add(message.reply_channel) message.reply_channel.send({"accept": True}) def ws_disconnect(message): Group("chat").send({'text': 'disconnected'}) Group("chat").discard(message.reply_channel) def ws_receive(message): Channel("chat").send({ "text": message.content['text'], }) I dont know it is true or not.. but please give me guidelines about that .. and which one is best way to use websockets? and also suggest me some links... -
Create loop like codeigniter in django
Controller : $data['all'] = SQL::get_data($this,tbl_menu,'*',array('parent_id'=>0),'urutan','',null)->result(); foreach ($data['all'] as $all){ $data['child'][$all->id] = SQL::get_data($this,tbl_menu,'*',array('parent_id'=>$all->id),'urutan','',null)->result(); } in View : <? $i = 1; foreach ($all as $a) { $i++; foreach($child[$a->id] as $c ){ }}?> I want code in codeigniter like this in apply in django how ? -
How to pass a Javascript variable in django template-tag
Hello i have this question if have a variable <script> var a = True <script> can i use the variable like {% if a %} <h1> True</h1> {%else%} <h1> False </h1> {%endif%} The both pieces of code are in the same page I don't want to use filters it will complicate a lot my work Thank you -
AJAX Post throws Broken Pipe and results in GET
I am sending a POST request via AJAX to Django server, after receiving the POST request by django it throws a "Broken Pipe error" and also initiates a GET request to same url but searching for "csrfmiddlewaretoken". Is this normal? How to avoid the GET request? [script] <script src="{% static 'js/jquery-3.3.1.min.js' %}"></script> <script src="{% static 'js/js_cookie.js' %}"></script> <script src="{% static 'js/csrf.js' %}"> </script> <script> function myfunc(){ $.ajax({ url: "help", type: 'POST', data: { "hello": "hello", }, }) } </script> [views.py] def help_view(request): if request.method == 'GET': return render(request, 'jsnapy_wizard/help.html') if request.method == 'POST': print request.POST return render(request, 'jsnapy_wizard/help.html') [urls.py] urlpatterns = [ url(r'help', help_view, name='help'), Error <QueryDict: {u'hello': [u'hello']}> [12/Jul/2018 07:17:37] "POST /help HTTP/1.1" 200 670 [2018-07-12 07:17:37,677] - Broken pipe from ('127.0.0.1', 49808) [12/Jul/2018 07:17:37] "GET /help?csrfmiddlewaretoken=nPvGEmGRGLhzGi7X3zRDFhElKLOaMR1CQbZoUA5lwPCCWbdkyVFEPLeE4vzfQ9pC HTTP/1.1" 200 670 -
Postgres with Django - Improperly configured. Error : ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'
After installing and configuring postgres using an online tutorial. I am attempting to run the command python manage.py makemigrations However I get the error ... ... File "/Users/raj/Development/mywebsite/virtual/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' This is in my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '..', 'USER':"...", "PASSWORD":"...", "HOST":"localhost", "PORT":"5432", } } Now I came across this thread which suggests that there might be an import issue. However If i import the package in the terminal like this it doesnt complain >>> import django.db.backends.postgresql_psycopg2 >>> Any suggestions on what I might be doing wrong here ? -
Getting a TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile
def post(self, request): form = CsvUploadForm(request.POST, request.FILES) if form.is_valid(): with open(request.FILES['csv']) as csv_source: has_header = csv.Sniffer().has_header(csv_source.read(1024)) csv_source.seek(0) reader = csv.DictReader(csv_source) .... .... return HttpResponse("file Uploaded") using the above code i am trying to upload a csv file and read it. but I am getting the following error. with open(request.FILES['csv']) as file: TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile what am i missing here ? django 2.0.7 python 3.5 -
Store 'Zero' for Null and Blank from django models
class Category(models.Model): parentId = models.ForeignKey('self', null=True, blank=True) category_name = models.CharField(max_length=100) inserted = models.DateTimeField(auto_now_add=True,null=True,blank=True) created = models.DateTimeField(auto_now=True,) want to store 'zero' in database, if the null=True and blank=True in parentID. -
Django - How to get model fields name for API using contentType or generic relation?
I am building Activity model like below. it has content_type as the target. class Activity(models.Model): user = models.ForeignKey(Auth, related_name='activity') content_type = models.ForeignKey(ContentType, null=True) object_id = models.PositiveIntegerField() doc_object = GenericForeignKey('content_type', 'object_id') Now we have created few models that is going to used in to Activity model like this. class Comment(models.Model): user = models.ForeignKey(Auth, related_name='comment') title = models.CharField(max_length=256) class Question(models.Model): user = models.ForeignKey(Auth, related_name='question') title = models.CharField(max_length=256) answer = models.TextField() class Like(models.Model): user = models.ForeignKey(Auth, related_name='like') status = models.BooleanField(default=False) I have written serializer like below class AtivityInstanceRelatedField(serializers.RelatedField): """ A custom field to use for the `tagged_object` generic relationship. """ def to_representation(self, value): """ Serialize tagged objects to a simple textual representation. """ if isinstance(value, Comment): return 'Comment: ' + value.title elif isinstance(value, Question): return 'Question: ' + value.title if isinstance(value, Like): return 'Like: ' + Like.status raise Exception('Unexpected type of tagged object') class AtivitySerializer(serializers.ModelSerializer): content_type = DocTemplateInstanceRelatedField(read_only=True) class Meta: model = Ativity fields = ['user','content_type'] our aspected output is to get field name in Method: option like { Comment:{ id, user, title, }, Question:{ id, user, title, answer, }, Like:{ id, user, status, } } How to Post data into the relevant model. Looking for much-needed help Thank you. -
Redis-Queue (RQ) Task Queues in Production
I recently started having a need for a task queue in my Django program, and I'm worried about how robust it will be in the future or what will need to be overcome for a production deployment. I'm using the Redis-Queue or RQ library for Python, which markets itself as easier to learn and use than something like Celery (which I haven't quite learned). Does anyone have any input on this? Do you think RQ coupled with Redis would be OK in production, or would you use something else? What do large-scale apps use for task queueing? -
Unable to serve static files correctly in Django app again
A couple of weeks ago I tried to install a django application in google cloud VM (Ubuntu 16.04). As I described in this post, I had issues serving the static files correctly in Django app. For some reason the url for the static files were not build correctly. I have fixed this issue by modifying my base.html template (where all the js and css is loaded) and using {% static %} instead of the STATIC_URL method as described here. Yesterday I tried to reinstall the application again in another frest VM but things for some reason do not work as expected. Although I made the above mentioned changes, I started getting the same errors as before: It seems like that the "static" string is missing from the URL. For example: instead of serving the js as: myIP/static/lib/css/assets.min.css it serves them as: myIP/lib/css/assets.min.css I am not sure why this happens as I define the STATIC_URL in my local_settings.py file. More over in my settings.py file I have set the paths to directories as: MEDIA_ROOT = '/var/www/geonode/uploaded' STATIC_ROOT = '/var/www/geonode/static/' TEMPLATE_DIRS = ( '/etc/geonode/templates', os.path.join(GEONODE_ROOT, 'templates'), ) # Additional directories which hold static files STATICFILES_DIRS = [ '/etc/geonode/media', os.path.join(GEONODE_ROOT, 'static'), ] My … -
Is there any way to debug Django apps running inside vagrant using VS Code?
I've been trying to debug an Open edX instance running inside their devstack using VS Code but the debugger keeps giving me the error. Debug adapter process has terminated unexpectedly Here is my launch.json { "name": "Python: Open edX", "type": "python", "request": "attach", "localRoot": "${workspaceFolder}", "remoteRoot": "/edx/app/edxapp/edx-platform/manage.py", "port": 2222, "host": "localhost", "secret": "my_secret", }, Also ptvsd inserted into the source code in manage.py import ptvsd ptvsd.enable_attach("my_secret", address = ('192.168.33.10', 8005)) ptvsd.wait_for_attach() -
Django RetrieveDestroyAPIView not working while requesting with vue.js
I had created a Django rest api and through vue.js function I implemented to delete the object by the id given to it, on clicking button i made function to pass the url with id given to api to delete the object. Django rest api works in it's rest api site but when it comes to access the api through vue.js function it's not deleting object and even no error also showing ---------- **#html code** <td v-on:click="deleteCountry(c.id)"><center><p class="fas fa-times"></p></center></td> // c.id is is dynamic id i am getting by django db ---------- **#vue.js code** <script> export default { data () { return { title:'app', }, methods:{ deleteCountry(id){ this.$http.get('http://127.0.0.1:8000/api/countries/'+id+'/delete/'); }, } } } </script> ---------- **django rest api viewsets code** from rest_framework .generics import( ListAPIView, RetrieveAPIView, DestroyAPIView, UpdateAPIView, RetrieveDestroyAPIView, RetrieveUpdateAPIView) class CountryDeleteAPIView(RetrieveDestroyAPIView): queryset = countries.objects.all() serializer_class = CountryDetailSerializer lookup_field = "id" -
open text for only one button, not for all
Im using bootstrap collapse and loops in my template to display data {% for text in imageTitles %} <div class="span4 collapse-group"> <div class="text-center"> <p><a class="btn btn-md btn-outline-dark btn-square" href="#">Check &raquo;</a></p> </div> <div class="collapse" id="collapseExample"> <div class="card card-body"> {{text}} </div> </div> <script> $('.btn').on('click', function(e) { e.preventDefault(); var $this = $(this); var $collapse = $this.closest('.collapse-group').find('.collapse'); $collapse.collapse('toggle'); }); </script> {% endfor %} when I press the button, then the text for each button is opened, but i need only for one, how to correctly write a function $('.btn').on('click', function(e) for correct operation -
How to host a django website in my pc and view it in another pc?
I have a django project in my pc. In terminal I've run python3 manage.py runserver <my ipaddress>:8001 When I try to open the link in another pc, it is showing error page which says: Invalid HTTP_HOST header: '<my ipaddress>:8001'. You may need to add '<my ipaddress>' to ALLOWED_HOSTS. What should I do? -
How to set the DjangoRestFramework permissin_classes relationship to `or`?
I have a AmodelCreateAPIView APIView: class AmodelCreateAPIView(CreateAPIView): serializer_class = AmodelSerializer permission_classes = [TokenHasReadWriteScope, TokenHasScope] queryset = Amodel.objects.all() as all we know the permission_classes list relationship is and, how can I let them become or? -
How to return json from django simple_tag
I am new to Django, here I have integrated amchart with my application. I have created a simple_tag method to set a value to dataProvider. Here my amchart code is, var chart = AmCharts.makeChart("chartdiv-{{ server.id }}", { "theme": "chalk", "type": "serial", "dataProvider": '{% get_space_occupation server.SpaceOccupied %}', "valueAxes": [{ "stackType": "3d", "unit": "GB", "position": "left", "title": "Memory space rate", }] When I try to return an array of hashes it is not returning the JSON as expected. Here my code in the custom template tag is, from django import template from django.http import JsonResponse from django.core import serializers @register.simple_tag def get_space_occupation(space_occupied): data = [{ "Drive": "C", "FreeSpace": 131, "Total": 250 }] # datas_serialized = serializers.serialize('json', data) return JsonResponse(data, safe=False) This is what I'm getting in my template, var chart = AmCharts.makeChart("chartdiv-1", { "theme": "chalk", "type": "serial", "dataProvider": '&lt;JsonResponse status_code=200, &quot;application/json&quot;&gt;', "valueAxes": [{ "stackType": "3d", "unit": "GB", "position": "left", "title": "Memory space rate", }] Please help me to resolve this issue and correct me if I were wrong. -
Django error while install channels
I'm trying to develop a chat application in Django based on websocket. I've tried to install Channels in virtualenv, with this commands: pip install channels and i got error this -
How to correctly display the message sent by each user? Django messaging app
I trying to make a messaging app with django. I am now trying to display the message within the private chat Like so However, the content written has no association as to who was the one who posted the message. I want it such that the sender's message appears on the left and the recipient's message appear on the right. Right now i have no way to show who, posted what. Any suggestions? Models.py class Message(models.Model): title = models.CharField(max_length=100, blank=True, null=True) content = models.TextField() sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='send_message') recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receive_message') parent_msg = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) sent_time = models.DateTimeField(auto_now=True, auto_now_add=False) read_reply = models.BooleanField(default=False) read = models.BooleanField(default=False) Views.py def read_message_view(request, pk): instance = Message.objects.get(pk=pk) if request.user != instance.sender and request.user != instance.recipient: raise Http404 form = ReplyMessageForm() object = Message.objects.get(pk=pk) if request.user == instance.recipient: instance.read = True instance.save() if request.user == instance.sender: instance.read_reply = True instance.save() context = { 'form': form, 'object': object } return render(request, 'private_messages/read.html', context) read.html <!-- Grid column --> <div class="col-md-6 col-xl-6 pl-md-3 px-lg-auto px-0"> <div class="chat-message"> <ul class="list-unstyled chat"> {% for child_comment in object.children %} {% if child_comment.sender %} <li class="d-flex justify-content-between mb-4"> {% if object.sender.profile.profile_picture %} <img src="{{ object.recipient.profile.profile_picture.url }}" alt="avatar" …