Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Include a django model object property using annotate()
I have a model that includes a @property that I want included when I do things like vals = MyModel.objects.values() Another S/O post suggests the way to do this is by overriding the get_queryset method of a manager class, augmented with a call to annotate(xtra_field=...). The problem is I can find no example of how to do this with a model property. I have tried things like super(SuperClass, self).get_queryset().annotate(xtra_fld=self.model.xtra_prop) and numerous variations thereof, none of which work. The question, I think is What should the RHS of the annotation argument(s) be? (And, yes, I know there are other, clunkier ways to do this, like iterating over what values() returns and adding the property as I go. Just not a very elegant (or even django) solution, to me. -
ModuleNotFoundError pycharm
Whenever i try to import any package that i installed previously i get following error. I can't figure out what i did wrong. C:\Users\David\Documents\Django_directory\usws15\eRoutes>python manage.py runserver 8002 Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001FF0416A6A8> Traceback (most recent call last): File "C:\Users\David\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\David\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "C:\Users\David\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Users\David\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\David\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\David\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\David\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\David\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 397, in check for pattern in self.url_patterns: File "C:\Users\David\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\David\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\David\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\David\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\David\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ...... "C:\Users\David\Documents\Django_directory\usws15\eRoutes\routing\urls.py", line 2, in <module> from . import views File "C:\Users\David\Documents\Django_directory\usws15\eRoutes\routing\views.py", line 2, in <module> import requests ModuleNotFoundError: No module named 'requests' -
Running mysqlclient on python with django
https://www.pythoncentral.io/writing-your-first-python-django-application/ I am following this tutorial on Django for Python. I have reached and installed the mysql-python (mysqlclient in python 3 which I am using) step. However I do not understand what he means by "..execute the following statements in a mysql shell.." mysql> CREATE USER 'pythoncentral'@'localhost' IDENTIFIED BY '12345'; mysql> CREATE DATABASE myblog; mysql> GRANT ALL ON myblog.* TO 'pythoncentral'@'localhost'; My problem is I do not know what program I need to enter these commands into. I have tried imputing the commands in: cmd.exe at the location of my django folder (myblog) on the mysql shell (https://dev.mysql.com/downloads/shell/) In the command window "python -m pip list" shows me mysqlclient is installed, however, python -m mysql (or mysqlclient, mysqldb etc) returns "No module named mysql" In the mysql shell, I have not been able to run the above commands either but I am less familiar with it compared to the command window. Any suggestions? -
Send data from django to AngularJs via channels
In my project I'm using django as backend and angularJS as frontend. To make the communication between both, I'm using channels in django and WebSockets in angularJS. For now, I just want to send data in one direction, from django to angularJS. In django I have correctly configured channels and I created the necessary files.(routing and consumers files) routing.py from channels.routing import route from buildings import consumers channel_routing = [ route('websocket.connect', consumers.ws_add, path = r'^/pablo/$'), route('websocket.receive', consumers.ws_message, path = r'^/pablo/$'), route('websocket.disconnect', consumers.ws_disconnect, path = r'^/pablo/$') ] consumers.py from channels import Group def ws_add(message): print('Received connection') message.reply_channel.send({'accept': True }) Group('pablo').add(message.reply_channel) def ws_message(message): print('Received message: {}'.format(message.content['text'])) Group('pablo').send({ 'text': message.content['text']}) def ws_disconnect(message): print('Finished connection') Group('pablo').discard(message.reply_channel) So from a python file in django I call to one function(handle_hal) to send data. python file in django: from channels import Group def handle_hal(self, topic, package): Group("pablo").send({ 'text': 'this text is not sent'}) For reduce mistakes, I replaced angularJs code by a plugin in chrome called Simple websocket client Steps Run django project Connect Simple websocket client to channels(In terminal Received connection message appears, it is the message of ws_add function) I execute the function handle_hal I can't see the message in Simple websocket client No errors … -
Can't Get Angular To Load Routes
I am making a local page following this tutorial, and it implements a login using django and angular. But I can't get the button register to show anything. It just changes the directory to /register. I think it has to do with routing. I get no errors. And I don't know how to debug this thing anymore, so I've run out of options. This is my first 'website'. Reason this isn't going smooth is because I did not get the starter project the tutorial came with. I wanted to learn how to implement this from scratch. This means my packages are newer (bootstrap, django, etc). Let me know if you need any more info, please. Thanks. index.html <!DOCTYPE html> <html ng-app="hawk"> <head> <title>Hawk</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> </head> <body> {% include 'navbar.html' %} <div class="container-fluid"> <div class="row"> <div class="col-xs-12 ng-view"></div> </div> </div> {% include 'javascripts.html' %} </body> </html> hawk.routes.js (function () { 'use strict'; angular .module('hawk.routes') .config(config); config.$inject = ['$routeProvider']; function config($routeProvider) { $routeProvider.when('/register', { controller: 'RegisterController', controllerAs: 'vm', templateUrl: '/static/templates/authentication/register.html' }).otherwise('/'); } })(); register.controller.js (function () { 'use strict'; angular .module('hawk.authentication.controllers') .controller('RegisterController', RegisterController); RegisterController.$inject = ['$location', '$scope', 'Authentication']; function RegisterController($location, $scope, Authentication) { var vm = this; vm.register = register; … -
How to use django as backend for cordova?
Not a web developer, but currently playing with cordova and would like to use django to use python to implement backend functionality. As I (vaguely) understand it, cordova manages frontend stuff and django is mostly for backend stuff. So is it possible to use django as a backend for a cordova project? If so, how? Is there some kind of special communicationn that I'd need to code myself? (My uneducated guess would be to initialize the django project inside the cordova www folder, but this seems wrong). And if this is a totally wrong way to think about this problem, let me know. -
Webmining Sentiment Analysis
Hello everyone I am working on a webmining project which uses the classification of sentiments Analysis and i am beginner, i could do the frontend of the website with django but i have'nt done yet the backend where i will have to include the datamining algorithmes! Can someone Help me or guide me please! i really searched a lot on the internet but as i said i am beginner on web and webmining i need some tutorials or examples to guide me!Can someone help me i can share with you the frontend with djungo -
How to remove a non-nullable field in Django?
I've got a category field in my model which I want to remove. However it did not have null=True so (from previous experience) deleting it will cause a django.db.utils.IntegrityError: null value in column “category” violates not-null constraint error. Any way around this? Here's is the field: class Post(models.Model): ... category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1') -
Django sentry - request.sentry object
I'm trying to enable the user-feedback functionality on my project. I tried several things with no success so far. I'm using django 1.11 and raven 6.8.0 I followed this solution too - [DOCS] Django Integration for User Feedback Debugging a little bit around the js snippet: {% if request.sentry.id %} <script> Raven.showReportDialog({ // grab the eventId generated by the Sentry SDK eventId: '{{ request.sentry.id }}', // use the public DSN (dont include your secret!) dsn: 'dsn' }); </script> {% endif %} I noticed that there's no sentry object inside request but the request object is present in the 500.html template Any help will be very appreciated -
DRF ValidationError not working for nested data structure
I'm parsing a nested data structure that I receive from a client using Django Rest Framework's ValidationError class in the exception module. The data structure looks something like this: { "business":"foo enterprises", "user": { "first_name":"foo", "last_name":"bar", } } When I parse this request and an error turns up on the top level of the structure such, ie: the client left out the business field, DRF returns the error in the following format: { "errors": [ { "source": { "pointer": "/data/attributes/business" }, "detail": "This field is required.", "status": "400" } ] } However when the client fails to include nested data such as the first name of the user, the format of the error is this: { "errors": [ { "first_name": [ "This field is required." ] } ] } The former is the format that I would prefer. Any clue as to what's happening here? -
I can't use django in coderunner 2
I have been trying to import and use django in python, and it cant import any modules I installed via pip. When I downloaded django on the command line it said in anaconda which was outside my user. So I tried to put it in my user d=and see if that would help but it didn't. -
Django regroup given a timezone
I am working on an application that displays some events to the user. I store the Event instance in UTC. Event has a datetime attribute start which I would like to use for some visual grouping. I created my Django template like so: {% regroup event_list by start.date as event_list_by_date %} {% for date in event_list_by_date %} <h2>{{ date.grouper }}</h2> {% for i in date.list %} <div> {{ i.start }} {{ i.subject }} </div> {% endfor %} {% endfor %} Which renders the following: May 18, 2018 May 18, 2018, 3 p.m. Meeting 928 May 18, 2018, midnight Meeting ABC May 18, 2018, 4 p.m. Meeting XYZ May 18, 2018, 3 p.m. Meeting 234 This is what I would expect when grouping by UTC dates. The problem is when I want to group by dates that respect a timezone; the datetimes are adjusted correctly, but the grouping is not adjusted for that timezone: {% timezone 'America/New_York' %} {% regroup event_list by start.date as event_list_by_date %} {% for date in event_list_by_date %} <h2>{{ date.grouper }}</h2> {% for i in date.list %} <div> {{ i.start }} {{ i.subject }} </div> {% endfor %} {% endfor %} {% endtimezone %} renders the following: … -
pgadmin3 - copy data from one database to another database on another server
I've been looking through many posts on SQL and copying data from one database to another but I'm having trouble. I am connected to two different databases through pgadmin3. I want to copy all the data from the tables (the columns are already set up). Let's say Database A - original database Database B - new, empty database to copy into on a different server The Database schemas were created using Django. Both tables have been migrated to the same migrations. Desired Results Copy Database A to Database B. What I've done so far I backed up Database A using pgadmin3. I've tried 'custom' and 'tar'. Then, I tried to restore Database B from the backup file, but hit a lot of errors that look like the following: pg_restore: creating SEQUENCE OWNED BY "public.samples_sample_id_seq" pg_restore: creating TABLE "public.samples_samplemetadata" pg_restore: [archiver (db)] Error from TOC entry 429; 1259 33715 TABLE samples_samplemetadata <user> pg_restore: [archiver (db)] could not execute query: ERROR: relation "samples_samplemetadata" already exists Command was: CREATE TABLE public.samples_samplemetadata ( id integer NOT NULL, value character varying(50) NOT NULL, attribut... pg_restore: [archiver (db)] could not execute query: ERROR: role "<user>" does not exist Command was: ALTER TABLE public.samples_samplemetadata OWNER TO <user>; … -
Passing additional form field from html to view in Django
I was following the post, when I try to solve my solution but it doesn't work for me. My problem: I have Django Model object with 4 attributes. lat say I have something like this class MyModel(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) first_at = models.IntegerField() second_at = models.IntegerField() third = models.TextField() Then I have some view in witch I would like to present form with this object. But, I would like to user only insert 2 of them, user and the third parameter need to be filled automatically. User from current user and third from another html element (In witch row the form was filled) class HomePage(LoginRequiredMixin, generic.CreateView): template_name = 'index.html' model = MyModel fields = ('first', 'second') success_url = reverse_lazy('home') def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) Then I have in HTML created <form action="." method="POST"> {% csrf_token %} {{ form.as_p }} <input type="hidden" name="third" value="{{ item.third }}" /> <input type="submit" value="submit" /> </form> Did anyone know why this is not working? And or how should I make it work, i there is a better way? Marko -
unable to run setting.py in a django project
i want to print my path in setting file like : print(os.path.abspath(file)) immediately after BASE.DIR, but doesn't work.it starts compiling whole file and report a syntaxerror on SECRET_KEY! how can i do that? because i saw someone could do that! thancks -
Document link on front end in Wagtail
If I upload a document to the Wagtail CMS, how can I make it available on the front end for download? Is there a specific template tag? -
django makemessages database strings
I'm looking for a way to configure django makemessages command to look for strings in some specific database columns and add them to the .po file. Solutions I've found involve storing the translations in the database, which I don't want to. How to add custom strings to be detected by makemessages command? -
Django Paypal not rendering form
I want users to be able to subscribe to my site using paypal. I've got all the permissions set up and its just the payment part I'm struggling with. I'm using Django-Paypal (here) but I'm having a problem rendering the form on the page itself. Views: def view_that_asks_for_money(request): # What you want the button to do. paypal_dict = { "business": "receiver_email@example.com", "amount": "10000000.00", "item_name": "name of the item", "invoice": "unique-invoice-id", "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('your-return-view')), "cancel_return": request.build_absolute_uri(reverse('your-cancel-view')), "custom": "premium_plan", # Custom command to correlate to some function later (optional) } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form} return render(request, "accounts/profile.html", context) On my HTML page I have got {{ form.render }} as everything has told me to do but it isnt showing up at all. -
CreateView and ModelForm with multiple models
I'm trying to expand the use of the official Django tutorial for practice purposes and to get more accustomed with Django since I'm new to it. The Django tutorial builds a polling app, in which only the Admin can add polls. I'm trying to expand that and allow registered users to be able to create polls too. For the users I'm using the built-in user model. My poll models are: class Poll(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') is_active = models.BooleanField(default=True) activation_date = models.DateTimeField('Activation Date', null=True) expiration_date = models.DateTimeField('Expiration Date', null=True) public_key = models.CharField(max_length=30, blank=True) hash = models.CharField(max_length=128, blank=True) timestamp = models.DateTimeField(auto_now=True) def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Choice(models.Model): question = models.ForeignKey(Poll, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class EligibleVoters(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) class PollKeyPart(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) encrypted_keypart = models.CharField(max_length=200, blank=True) decrypted_keypart = models.CharField(max_length=200, blank=True) class Voter(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) class PollVotes(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE) vote = models.CharField(max_length=200) class Voter(models.Model): user = … -
django orm get foreign key values
I have two tables, class A(models.Model): name = models.CharField(max_length=1000, unique=True) class B(models.Model): name = models.CharField(max_length=1000, unique=True) a = models.ForeignKey(A, on_delete=models.PROTECT, related_name="a") I need the result set as follows, { "name":"test", "a":[ {"name":"a1"}, {"name":"b1"}, {"name":"c1"}] } Sample table data A id name ------------ 1 a B id name a --------------- 1 a1 1 2 b1 1 3 c1 1 How would I achieve my desired result in django orm? I tried a_ob = A.objects.get(id=1) b_ob = a_ob.a.all() which would give me two results and i would combine both. When I want to get all records in table A, what would I use. (without for loop in orm) -
Calling a form based on a string within a view
I'm building out a view within django that will be used to drive the display of several different forms. Each form name is stored within a model instance and is called within the view. Despite the fact that I have this form name, I'm not sure how I can call the form using a string that is equal to the form's name. For example, normally, within a view, you might see something like this for a form called myOwnForm. form = myOwnForm(request.POST, request.FILES, instance=instance) In my case, the string of 'myOwnForm' is stored in the field formname of myFormModel. As a result, I've tried this. formname = myFormModel.formname form = formname(request.POST, request.FILES, instance=instance) This fails to call the myOwnForm form. Would you happen to know how I might be able to call the form name using a string that is stored in a variable? Thank you! -
Django template iterating a queryset with a for loop counter
I have 3 query sets for 3 different types of articles: Right leaning, center, left leaning. I am trying to display these in 3 columns so it would come out as: Right Lean | Center Lean | Left Lean Right Lean | Center Lean | Left Lean Right Lean | Center Lean | Left Lean So, I have these in three query sets, like this in the view: right_articles = sline.article_set.filter(avgLean__lte=-0.75).order_by('-credibility')[:25] left_articles = sline.article_set.filter(avgLean__gte=0.75).order_by('-credibility')[:25] center_articles = sline.article_set.filter(avgLean__gt=-0.75).filter(avgLean__lt=0.75).order_by('-credibility')[:25] And I added a counter for how many I want in each column as part of the context like this: return render(request, 'storylines/detail.html', {'n_articles': range(0, 24),'storyline': sline, 'reqUser':request.user, 'vote':ini, 'right_articles':right_articles, 'left_articles': left_articles, 'center_articles': center_articles}) Then I go to the template and loop through those like this: <div class="row"> <div class= "col-4"> Left articles: {{ left_articles.count }} </div> <div class= "col-4"> Center articles: {{ center_articles.count }} </div> <div class= "col-4"> Right articles: {{ right_articles.count }} </div> </div> {% for i in n_articles %} <div class="row"> Trying {{ i }}<br> {% with left_articles.i as lt_article %} {% if lt_article %} {% show_card lt_article %} {% else %} <div class="col-4">No Left article {{ i }}</div> {% endif %} {% endwith %} {% with center_articles.i as cn_article … -
Python Django: change font color for part of string found in another tuple
Here are the tuples in views.py: my_list1 = ['I like the hotel.','I like the red car and the tree.'] my_list2 = ['hotel','tree','red car'] Here is what I'm trying to do on index.html: I like the <font color="red">hotel</font>. I like the <font color="red">red car</font> and the <font color="red">tree</font>. On index.html, I have the following to make the entire item in red. But, I cannot change font color for the items found in my_list2 only. Please help! <table> {% for item in my_list1 %} <tr> <td id="red">{{item}}</td> </tr> {% endfor %} </table> -
Django Landing page
I know that in Django for example if I have the home app, I can create it's landing page so that when a user goes to domain/my_app, it directs them to the index of that app. Now I want to do the same for the whole website, a global landing page, so it will stop giving me a 404 when I reach to domain/ -
LastPass Ignore and Crispy Forms
My goal is to have LastPass ignore all input forms on my site. I am using crispy forms and showing all form fields with only this in my HTML: {{ form|crispy }} However, I want to edit some of the HTML attributes of all input elements created by this form WITHOUT writing each one individually. LastPass recommends that I use data-lpignore="true" in my HTML input tags. I tried to implement that in my form tags, but that didn't work (yes, I know, form != input). : <form action="{{ action }}" method="post" class="no-ajax" data-lpignore="true"> {% csrf_token %} {{ form|crispy }} <input type="submit" name="submit" value="Save" class="btn btn-primary btn-lg" /> </form> This didn't work. I also tried including the following in SETTINGS.py: CRISPY_CLASS_CONVERTERS = {'data-lpignore': 'true'} Which is supposed to add data-lpignore="true" to my crispy form input tags according to crispy forms' documentation, but this didn't work. Am I stuck doing individual input lines or is there a better solution?