Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I split a django rest app on 2 ports
I have a django project which implements 2 separate rest apis. Both share a considerable amount of backend logic, and are implemented as separate apps within a single site. I have a requirement that the apis must run on different ports such that the end-user can use their existing firewall to control access to the two rest apis. Right now, I have one url configuration which routes between the two apps. e.g. urlpatterns = [ path("oper/api/v1", include("operator.urls"), path("user/api/v1", include("user.urls"), ] I also have a systemd service script launch the django application as a service. My plan is to have 2 systemd service scripts, one for the operator api, and the other for the user api. When run in development mode, I would like both rest apis to appear as one, such that requesting dev-host:8080/oper/api/v1 would route to the 'operator.urls' module and dev-host:8080/user/api/v1 would route to the 'user.urls' module. I'm thinking of using an environment variable to make the distinction, e.g. if DJANGO_ENV=operator_prod it would start the server on port 8081 and only accept the 'oper/api/v1' endpoint. And if DJANGO_ENV=user_prod it would start on port 8082 and only accept the 'user/api/v1' endpoint. But if the DJANGO_ENV wasn't set, or was set … -
How to enforce Django to use "JOIN VALUES"
I'm having a performance problem where I need to replace section of my query statement. Right now I have a the following: select count(*) FROM "mytable" WHERE "field" IN ('v1', 'v2', ..., 'vN'); this can be translated to Django ORM: Mytable.objects.all().filter(field__in=[myvalues]).count() I need to do the following though: select count(*) FROM "mytable" JOIN (values ('v1', 'v2', ..., 'vN')) as lookup(value) on lookup.value = "mytable".field; Is there a way to add this to the ORM? I need to do with ORM because I already have other filters. Worst case scenario I thought of getting the query string and adding there manually... -
Django filter get at least n records
Is there an efficient way to get at least n records for a given filter and order? More specifically, I want to get a list of all entries in a model that have a certain date field greater than a month ago, but in case there are less than 10 such entries, then get at least 10 of such entries. I can do this by getting the count, then checking and making the query again, but was wondering if there was a better way to do it. -
Django- Can your view function see which URL it is being called from?
The reason I ask is that if this is possible I would like to include logic in my view so I can reuse the same function. I would like to do something along the lines of: urlpatterns = [ path(site1, views.function), path(site2, views.function) ] def function: if "site1/": # do this elif "site2/": # do something else I would be calling the urls by their name attribute to keep it future proof. -
Extracting Admin ManyToManyField to CSV file
I'm currently trying to learn django. I'm working on a personal project. I'm trying to create an action in the admin panel for extracting data from my model to a CSV File. For example, I have the following Model: class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) type_product = models.ForeignKey(Sous_Categories_Article, verbose_name="Catégorie Article", on_delete=models.PROTECT) product = models.ManyToManyField(Variations_Articles, max_length=1000, verbose_name='Article') price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) I use the following code at that time: def export_to_csv(modeladmin, request, queryset): opts = modeladmin.model._meta response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_') writer = csv.writer(response) fields = [] fields = [field for field in opts.get_fields()] writer.writerow([field.name.title() for field in fields]) for obj in queryset: data_row = [] for field in fields: if field.many_to_many == True or field.one_to_many == True : values = obj.product.all().values_list('id', flat=True) for value in values: data_row.append(value) else: value = getattr(obj, field.name) data_row.append(value) if isinstance(value, datetime.datetime): value = value.strftime('%d/%m/%Y') writer.writerow(data_row) return response export_to_csv.short_description = 'Export to CSV' I have two questions. I like to extract other models that have ManyToManyField or One to Many Field. How can i proceed? The following code only applies to a specific Model: values = obj.product.all().values_list('id', flat=True) How can I use a "variable" in my query … -
Django test data persisting across multiple tests despite being TestCase
I have a a test case that uses setUp and looks like this: from django.test import TestCase, Client, TransactionTestCase ... class TestPancakeView(TestCase): def setUp(self): self.client = Client() # The Year objects are empty (none here - expected) print(Year.objects.all()) # When I run these Test by itself, these are empty (expected) # When I run the whole file, this prints out a number of # Pancake objects causing these tests to fail - these objects appear # to be persisting from previous tests print(Pancake.objects.all()) # This sets up my mock/test data data_setup.basic_setup(self) # This now prints out the expected years that data_setup creates print(Year.objects.all()) # This prints all the objects that I should have # But if the whole file is ran - it's printing objects # That were created in other tests print(Pancake.objects.all()) [...tests and such...] data_setup.py is a file that just creates all the appropriate test-data for my tests when it needs them. I'm using Factory Boy for creating test data. When I run TestPancakeView by itself - my tests pass as expected. When I run my entire test_views.py file, my TestPancakeView tests fail. If I change it to TransactionTestCase - it still fails when I run the whole … -
Tensorflow: Module must be applied in the graph it was instantiated for
I'm trying to serve universal sentence encoder with Django. The code is initialized in the beginning as a background process (by using programs such as supervisor), then it communicates with Django using TCP sockets and eventually returns encoded sentence. import socket from threading import Thread import tensorflow as tf import tensorflow_hub as hub import atexit # Pre-loading the variables: embed = hub.Module("https://tfhub.dev/google/universal-sentence-encoder/2") session = tf.Session() session.run(tf.global_variables_initializer()) session.run(tf.tables_initializer()) atexit.register(session.close) # session closes if the script is halted ... # Converts string to vector embedding: def initiate_connection(conn): data = conn.recv(1024) conn.send(session.run(embed([data]))) conn.close() # Process in background, waiting for TCP message from views.py while True: conn, addr = _socket.accept() _thread = Thread(target=initiate_connection, args=(conn,)) # new thread for each request (could be limited later) _thread.demon = True _thread.start() conn.close() But I receive the following error: RuntimeError: Module must be applied in the graph it was instantiated for. I'm basically trying to pre-load table in tensorflow (because it takes quite a lot of time), but tensorflow doesn't let me use the session that was pre-defined. How can I fix this? Is there any way to pre-load these variables? P.S I believe this Github issue page might have solution for my problem, but I'm not sure … -
Adding validation error message to classed based view (CreateView)
In models.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='post_pics', blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I want to add a ValidationError Message to 'image' field: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content', 'image'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) If user uploads something else in image field the form won't submit, which is fine, but I would like to add extra message something like "Images only..". Ideally combine multiple errors (size or resolution). I would like to keep the structure of view as class based, so without going into forms.py or making a function based view. Thanks in advance. -
Heroku Scheduler give this error in script (Django app)
The error is this: File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/app/misuper/management/commands/enviar_facturas_erp_manual.py", line 46, in handle message.send() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/mail/message.py", line 302, in get_connection self.connection = get_connection(fail_silently=fail_silently) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/mail/__init__.py", line 36, in get_connection klass = import_string(backend or settings.EMAIL_BACKEND) File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/app/.heroku/python/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named smtp Yes, you can tell me, install the package (?), but is already in the app, in all other process i can send emails, except in this script! The sending code of email is this: message = EmailMessage("xxxx", "xxxx", "xxx@xxx", ["xxxx@xxxx"]) message.attach('xxx.csv', csvfile.getvalue(), 'text/csv') message.send() logger.info(len(send_orders)) I running the script in a Standard 1X Dyno -
Can I use Python 3.7 with Django 1.11?
We have an existing Django application which uses Django 1.11 and Python 3.6. For some security reasons I have been asked to use Python 3.7. I need to make the minimum changes possible. Do I need to upgrade Django as well? If so , is there any code changes required? Thanks, -
Accessing Attributes of a CheckboxSelectMultiple checkbox
Short Version In the Django template language, how do I access the attributes of a given checkbox within a CheckboxSelectMultiple widget? Long Version The attributes of a typical Django widget can be accessed easily: {% for field in form %} {{ field.widget.attrs.something }} {% endfor %} However, this method isn't working for a checkbox within a CheckboxSelectMultiple widget. I have a customized CheckboxSelectMultiple widget which I'm using to display a ManyToMany ModelForm field. The customized widget adds additional attributes to each checkbox in the create_option method. The additional attributes display appropriately within the HTML of the input element: <input type="checkbox" name="questions" value="22" id="id_questions_12" category="Category Name" category_number="3" question="Question Name" question_number="4"> I need to access these additional attributes for purposes of display and organizing the form fields. -
Using Template Specific JavaScript in Django
I have a base_generic.html page in django that has the standard UI elements (navbar, footer, etc.), and I have a list.html page which extends the base_generic.html page. The list.html page is using a javascript function that is only used in this page, but for it to work, I have to include it in the base_generic.html page. How can I include this javascript function in list.html using Django's built-in template tags and features? Should I use {% verbatim %} or {% scripts %} or another tag template? Should I include this inline with the {% block content %} that has the html for this django template, or should I place it before or after the {% block content %}? -
Programy chatbot executes Django command
I am studying the way to integrate programy to my Django application. First thing I would like to see is chatbot be able to execute Django-command. For example I: How many orders are created today? bot: They are {{ Order.objects.filter(...).count() }} orders When I look at the document. It mentions only AIML, but does not mention anything about execute further command. Possible workaround: It seems to be impossible since <set>, <get> tags are static and programy has to compile and loaded into the memory before bot start conversation. Drawback: Doing the pre-queries and set the variable. Bot will present the outdated value. Question: How do I let bot execute Django by itself? -
How to search django Postgres table textarea field for multiple words?
I am creating a recruitment website, and i need to search a keys skills text area field, for multiple values. eg. I may be looking for a C++ programmer with good python, and worked in healthcare data scientist. so my search entry form i would put c++ python healthcare data scientist. there could be up to 20 staff performing searches against a database with a few thousand records. I need to know what is the best technology to perform this type of search with Django and postresql database hosted on digitalocean. -
Django; do I need to collect static files for admin in order to configure django-allauth in production?
I configured django-allauth in development. And it does work on local site. But it doesn't work on production (elasticbeanstalk). I added both site to the Site. Because I didn't collect static files for admin site, I cannot go to admin site in production yet. Do I need to collect static files for admin site so I can configure django-allauth on admin site in production? Or I might make other mistake. Honestly, I still don't get what SITE_ID means. Does it need to match the ID of the site I added to admin? What if I want to try to run the app on multiple domains like both local and development? -
Why am i getting __init__() takes 1 positional argument but 2 were given?
I am working on a project and I am getting this following error: traceback: TypeError at /account/reset-password __init__() takes 1 positional argument but 2 were given imports: from django.conf.urls import url from . import views from django.contrib.auth import views as auth_views from django.contrib.auth.views import PasswordResetView, PasswordResetDoneView url: url(r'^reset-password$', PasswordResetView, name='reset_password'), I am new to django, so welcomed help . ty -
Update method isn't working [DjangoRestFramework]
I am trying to abstract my endpoints by using the Viewsets and for some reasons the update() method to one of the endpoints isn't saving an updated field. How do I update the fields? NB: I am testing using Postman using PUT method serializers.py: class UpdateArticleSerializer(serializers.Serializer): title = serializers.CharField(max_length=250, required=True) body = serializers.CharField() image_url = serializers.URLField() keypoint = serializers.ListField() country = CountrySerializer(read_only=True) category = CategorySerializer(read_only=True) def create(self, validated_data): return Article(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.body = validated_data.get('body', instance.body) instance.image_url = validated_data.get('image_url', instance.image_url) instance.keypoint = validated_data.get('keypoint', instance.keypoint) instance.country = validated_data.get('country', instance.country) instance.category = validated_data.get('category', instance.category) instance.save() return instance views.py [update method]: def update(self, request, pk=None): article = Article.objects.get(id=pk) serializer = UpdateArticleSerializer(data=request.data) if article.author == request.user: if article.is_published != True: if serializer.is_valid(): serializer.save(author=request.user) queryset = article serializer = ArticleSerializer(queryset) return Response(jsend.success({'post':serializer.data}), status=status.HTTP_200_OK) else: return Response((jsend.error('Published post cannot be edited')), status=status.HTTP_409_CONFLICT) else: return Response((jsend.error("You are not authorized to perform this action")), status=status.HTTP_403_FORBIDDEN) -
Why is my form template not getting displayed in Django project
So I am new to django and I am sure this is not a very good question. I am working on a project in which I have a form (for database entry) for user. It is supposed to show up after I click on a link i;e Add E-Shop, yet when I click on it, I remain on the same page (even though the url is changed) The redirecting link is like this: <li class="nav-item" > <a class="nav-link" style="color: #ffffff" href="{%url "main:add-shop"%}">Add E-Shop</a> </li> My views.py file is below: def emarket(request): if not request.user.is_authenticated: return HttpResponseRedirect('/login/') emarket = Emarket.objects.all().exclude(verify = False) pos = Emarket.objects.values_list('latt', 'lonn') a = np.array(pos) lat1=[] long1=[] for i in range(len(a)): lat1.append(a[i][0]) long1.append(a[i][1]) return render(request, 'main/emarket.html', {"emarket": emarket ,'lat' : lat1 , 'lng':long1 }) class AddShop(CreateView): #this is my adding shop model model = Emarket fields = ['name', 'owner', 'city_location', 'description', 'logo', 'latt', 'lonn'] And following is my urls configuration: from django.conf.urls import url from . import views app_name = 'main' urlpatterns = [ url(r'^home/', views.index, name='index'), # Home page url(r'e-market/', views.emarket, name = 'emarket'), # rain water url(r'e-market/add-eShop/$', views.AddShop.as_view(), name = 'add-shop'), # Add an E shop ] My form template is by the name 'shop_form.html' … -
Django Infinite Scroll, everythin appear, but no scroll, only a more button
I want to use django infinite scroll on my blog page where all my posts are listed, i followed the guide but i get a problem, my posts do appear, and they only show the amount specified in view BUT, the scroll doesnt work, i need to click on the more button to see next page model class Post(models.Model): title = models.CharField(max_length = 140) slug = models.SlugField(max_length=40, blank=True) image = models.ImageField(upload_to="media", blank=True) body = RichTextField(config_name='default') date = models.DateField() #sites = models.ManyToManyField(Site) sites = models.ForeignKey(Site,null=True, on_delete=models.CASCADE) def __str__(self): return self.slug def approved_comments(self): return self.comments.filter(approved_comment=True) url url(r'^$', views.listingPost, name='blog'), view def listingPost(request): post_list = Post.objects.all().order_by("-date") page = request.GET.get('page', 1) paginator = Paginator(post_list, 6) try: post = paginator.page(page) except PageNotAnInteger: post = paginator.page(1) except EmptyPage: post = paginator.page(paginator.num_pages) return render(request, 'blog/blog.html', {'post': post}) in the html .infinite-item, .loading { margin-bottom: 5px; background-color: #1eaedb; color: #fff; text-align: center; padding: 25px 0; } .loading { background-color: #333; <div class="infinite-container waypoint"> {% for post in post %} <div class="infinite-item">{{ post.title }}</div> {% endfor %} </div> <div class="loading" style="display: none;"> Loading... </div> {% if post.has_next %} <a class="infinite-more-link" href="?page={{ post.next_page_number }}">More</a> {% endif %} <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/jquery.waypoints.min.js' %}"></script> <script src="{% static … -
Detect MySql changes and send post data to a remote server
I am building a system that would send post data to an endpoint of an API once it detects a change in the database of a locally running MySql server. To better explain the scenario here is what the system is expected to do - Run as a process on a local system Detect changes on a database of MySql. Note: MySql is running on the local system. Once a change is detected it sends the data to an API endpoint. I got to know that in the industry a POS(Point of Sale) file is used to send database data. But I don't want to proceed that way. Current Solution - The solution which I can think of now is to build a standalone Django application that would detect changes in the database using Django Signals, and then send POST data accordingly to the endpoint. But I really don't know if its the best way to build it. Please let me know what could be the best way to build such a system. Thanks -
Scheduled task with Django
I'm working on a web app which manages events. I store data about them such as their starting time. I would like to execute a task (in this case, sending a mail to the event administrator). There shouldn't be there more than 10 events a day and the sending would just involve one mail. I've been reading about different approaches such as a writing custom command amd executing it with cron, but as long as the sending time depends on each event, I think it wouldn't be a nice solution. I have read as well about Celery, but in this case I think that would be a too powerful and heavy tool for my needs. Is there any other alternative? -
How read barcode django
i'm try to read barcode/QR from camera with django, i'm using pyzbar this is my code: myfile = request.FILES['image_from_camera'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) data = decode(Image.open("media/"+myfile.name)) print(data) #output [] in this case return empty, this is the image capture from camera this is the original image(that i try capture): also try convert the image to black and white: import pytesseract from PIL import ImageEnhance, ImageFilter from PIL import Image as Img im = Img.open("media/"+myfile.name) im = im.filter(ImageFilter.MedianFilter()) enhancer = ImageEnhance.Contrast(im) im = enhancer.enhance(15) im = im.convert('1') im.save('media/sample.jpeg') im_temp = cv2.imread("media/" + myfile.name) data = decode(im_temp) print (data) #output [] the imagen with black and white effect: get the same result..empty..please any suggest..or idea.. thanks..!! -
Django runserver in windows just aborts with no error message
I have been developing a Django project with some of the programmers using windows. Suddenly, all of them are unable to go on because runserver just aborts when accessing the port from the web browser. Just like that, with no error message or anything. I guess it is windows issue because programmers with mac have no problem at all, and all windows pcs got the problem at the same time. Has anybody known about any Windows issue lately and have any reference to try to find the solution? It, is a critical situation. -
Django runserver stop
I running Django localhost server with PostgreSQL database:python manage.py runserver But when I use the browser to consult the project, the server stops like I put in the console Ctrl + C. I don't get any error messege from Python, so I don't know whats happen. -
Nesting JSON Api Comments with Replies
Am new in Django, and I was developing a simple Django application which is all about writing blogs. this application has the functionality of writing Replies under Comments. But I have failed to achieve that. With the help of the JSON format example let me show you what I want to achieve: If you look clearly in this JSON script, the comment has a nested replies "comments": [ { "id": 2, "created_at": "2018-09-18T07:15:51.134585Z", "body": "There's n one to take today", "article": 4, "author": 1 }, { "id": 1, "created_at": "2018-09-17T18:15:57.284529Z", "body": "There's n one to take today", "article": 4, "author": 1 "replies":[ "content":"Hey hello", "created_at":"2018-09-18T09" ] } ] The example above is what I want to achieve but it doesn't work. This is a full JSON script it's showing in POSTMAN : { "articles": { "links": { "next": null, "previous": null }, "count": 4, "results": [ { "slug": "its-me-there-hello-am-available-today-theres-n-one-to-take-today-20180917091132412928", "title": "It's me there.", "description": "Hello am available today , what of you there.", "body": "There's n one to take today", "created_at": "2018-09-17T09:11:32.409751Z", "updated_at": "2018-09-17T09:11:32.409741Z", "favorited": false, "favorites_count": 0, "photo_url": null, "author": { "username": "jhild23", "bio": null, "first_name": null, "last_name": null, "location": null }, "comments": [ { "id": 2, "created_at": "2018-09-18T07:15:51.134585Z", …