Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use gettext in Heroku
Things doing well in my local system. I want to compile i18l.po in Django system which I deployed on heroku. When i run heroku run python manage.py compilemessages -l en I got error saying "CommandError: Can't find msgfmt. Make sure you have GNU gettext tools 0.15 or newer installed." It meas that there's no gettext module in heroku? Then I tried to install gettext in heroku CLI. Then I run heroku create --buildpack https://github.com/piotras/heroku-buildpack-gettext.git to do that. But I failed. -
What does LogEntry do?
I am just curious, because I can't find what it is anywhere online. I looked at Django's documentation and it just tells you what's inside it, I guess? I'm just curious because it is being used in some code I'm looking at and I need to know if it's important. Here's the code I'm looking at. LogEntry.objects.create( user_id = request.user.pk, content_type_id = ContentType.objects.get_for_model(SummerInfo).pk, object_id = SummerInfo.pk, object_repr = (request.user.first_name + ' ' + request.user.last_name), action_flag = 2, change_message = 'Completed/Updated Summer Intent Form' ) ''' -
How to create tree panel in Extjs with son json data
I want to generate a tree panel, when I define the TreeStore I get the following error: 'Cannot read property 'isModel' of undefined. Here is some fragment of my code: Ext.define('App.view.AreaActivosTree', { extend: 'Ext.panel.Panel', alias: 'widget.AreaActivosTree', requires: ['Ext.toolbar.Toolbar', 'Ext.data.*', 'Ext.grid.*', 'Ext.tree.*', 'Ext.tip.*'], initComponent: function() { var store = Ext.create('Ext.data.TreeStore', { proxy:{ type: 'ajax', url: 'principal/app/tree_areas_versat/', reader: { type: 'json', root: 'root', } }, autoLoad:true, }); Ext.apply(this, { items: [{ xtype: 'treepanel', rootVisible: false, store: store, }], }); this.callParent(arguments); }, }); json que devuelve url: {"total": 73, "root": {"expanded": true, "children": [{"text": "AREA VICEPRESIDENCIA COMERCIAL", "expanded": true, "children": [{"text": "DIRECCI\u00d3N COMERCIAL LOGISTICA DE ALMACEN", "leaf": true}, {"text": "DIRECCI\u00d3N COMERCIAL MARKETING Y VENTAS", "leaf": true}, {"text": "DIRECCI\u00d3N COMERCIAL NUEVOS NEGOCIOS", "leaf": true}, {"text": "DIRECCI\u00d3N COMERCIAL TRANSPORTE Y SEGURO", "leaf": true}, {"text": "VICEPRESIDENCIA COMERCIAL", "leaf": true}, {"text": "OFICINA SECRETARIA VICE PRESIDENCIA COMERCIAL", "leaf": true}]}, {"text": "AREA DIRECCION DE INSPECCION DEL TRANSPORTE", "expanded": true, "children": [{"text": "DIRECCION DE INSPECCION DEL TRANSPORTE", "leaf": true}, {"text": "GPS", "leaf": true}]}, {"text": "AREA VICEPRESIDENCIA LOGISTICA", "expanded": true, "children": [{"text": "VICEPRESIDENCIA LOGISTICA", "leaf": true}, {"text": "DIRECCI\u00d3N DE GESTI\u00d3N DE LOS RECURSO E INVENTARIOS", "leaf": true}, {"text": "GRUPO ADMINISTRACI\u00d3N", "leaf": true}]}, {"text": "TRANSPORTE", "expanded": true, "children": [{"text": "DIRECCION", "leaf": true}]}, … -
Django / Paypal - Uncaught TypeError: Cannot read property 'supportOneTouchLoginOn8ball' of null
I am getting the error bellow when I click the button to go the paypal page, the error goes to console. the page shows a loop with the text: Securely logging you in... You activated PayPal One Touch™, so no need to enter your password today. It stays here permanently. Uncaught TypeError: Cannot read property 'supportOneTouchLoginOn8ball' of null at hermes?token=96N01477KD7295421&useraction=commit&mfid=1557861060485_15a0fd2aec52d:1 at hermes?token=96N01477KD7295421&useraction=commit&mfid=1557861060485_15a0fd2aec52d:1 at hermes?token=96N01477KD7295421&useraction=commit&mfid=1557861060485_15a0fd2aec52d:1 (anonymous) @ hermes?token=96N01477KD7295421&useraction=commit&mfid=1557861060485_15a0fd2aec52d:1 (anonymous) @ hermes?token=96N01477KD7295421&useraction=commit&mfid=1557861060485_15a0fd2aec52d:1 (anonymous) @ hermes?token=96N01477KD7295421&useraction=commit&mfid=1557861060485_15a0fd2aec52d:1 It started with chrome, then in firefox and edge. Everything was working correctly two days ago, It works in safari in my phone, so I suspect it might have something to do with my computer, How can I overcome this? -
Django: include paths with pk
I'm developping an app that uses context processors, the function within the context processors is executed only if it doesn't belong to any of the paths specified as follows: if request.path != "/details/" and \ request.path != "/live/": # EXECUTE FUNCTIONS However, I'm not managing to include a path that has pk included on it. I've tried the following: request.path != "/live/<int:pk> without results. Any ideas? thanks! -
How would you design database relationships based from the following data..?
How would you frame the data in a relational database? When I update the database I would like to add a corresponding batch number (batch_no) to both tables so that data can be linked. How would I do this? First table are the classification results from the batch. +--------------+-----------+--------+----------+---------+----------+ | | precision | recall | f1-score | support | batch_no | +--------------+-----------+--------+----------+---------+----------+ | | | | | | | | positive | 0.56 | 0.7 | 0.62 | 1034 | 1 | | negative | 0.96 | 0.94 | 0.95 | 8966 | 1 | | | | | | | | | micro avg | 0.91 | 0.91 | 0.91 | 10000 | 1 | | macro avg | 0.76 | 0.82 | 0.79 | 10000 | 1 | | weighted avg | 0.92 | 0.91 | 0.92 | 10000 | 1 | +--------------+-----------+--------+----------+---------+----------+ Second table are the many reviews. +------------+-----------+--------+----------+ | reviewtext | predicted | actual | batch_no | +------------+-----------+--------+----------+ | blah blah | pos | neg | 1 | | blah blah | pos | pos | 1 | | blah blah | neg | neg | 1 | +------------+-----------+--------+----------+ I've tried experimenting with composite keys and … -
MySQL DB is not starting in Django Python
When I start my server in Django and try to connect the MySql with it. This error appears :/ how to resolve it raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__) django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. My python version is 3.7.3 and Django version is 2.2.1. Please guide me. I have seen videos on YouTube but still no help. Thanks in Advance -
Retrieve the src attribute given to an iframe by the parent page within an inside the iframe in django CBV
I am collaborating with someone that has developed a portal page which contains links to apps. When clicked the link, my app is loaded in an iFrame and is appended a ?tonkenid in the url; I don't control the portal page. I would like to get the src attr of the iFrame and parse the tokenid as I need it to use it from my app loaded in the iframe to make API calls. Just to be clear, here is what I have, after authenticated in the portal: The portal (once authenticated) Linktoapp1 Linktoapp2 i-frame Here my app is loaded. When I inspect the relevant part in the browser I get this: <body> <div id="content"> <iframe id="module" src="https://www.myappurl.com/?tokenid=.eJwty8GKgzAQANB_mbMUjWmS8bT_URaZmFEGYlwcw1ZK_72y7PEd3gskcTnkOGF4wb5lVhgeEKvkJGUZVyq08A7fDRznD8MAVS82UCVdyFV0laVyvsVMhXVnPbbzq1RZKP_SeROGdwNKax4LrTz-Nd8itXNMFl2P5Hg2NnjDPPk4JWPu3qPHmRP8T2VV2cqVn9ce78725HzfTTx7tC3G1KLpU0wdOofOMrvQhRAsvD8ho0j5.XNrWyw.8IMfiT9YcfZKGbqedHOHYyDnjVg"> </div> </body> So I need to retrieve this tokenid that is generated and appended by the portal from within the app itself. I tried many recipes and it seems impossible. I tried this: <script> function myFunction() { var res = window.parent.document.getElementById('module')src; document.getElementById("demo").innerHTML = res; } </script> but it gives me SecurityError: Permission denied to access property "document" on cross-origin object I also tried with python requests and urrlib with no success.Is there any other recipe for a django based app to scrap … -
Filtering items using drop down list
Would like to filter features(products) by using dropdown menu. Each of the feature(product) got a tag (e.g. food, drink, random). Idea is when user selects the tag on a menu, it shows only those items who's got that tag. So far I went as far, but doesn't seem to work yet. PyCharm does not give an error, but not functioning. What I am missing? Thank you! my models.py class Feature(models.Model): FOOD = 'food' DRINK = 'drink' RANDOM = 'random' TAGS = ( (FOOD, 'food'), (DRINK, 'drink'), (RANDOM, 'random') ) name = models.CharField(max_length=40, default='') tags = models.CharField(max_length=20, choices=TAGS, default=ALL) def __str__(self): return self.name my views.py def tags(request): if request.GET.get('tags'): features_filter = request.GET.get('tags') listings = Feature.objects.filter(features_filter=features_filter) else: listings = Feature.objects.all() context = {'listings': listings} return render(request, 'features', context) my features.html <form action="{% url 'features' %}" method="get" accept-charset="utf-8"> {% csrf_token %} <select name="tags"> {% for feat in features %} <option value="{{feat.tags}}">{{ feat.tags }}</option> {% endfor %} </select> <input type="submit" value="submit"> </form> {% for feature in features %} <h1{{ feature.name }}</strong></h1> {% endfor %} -
How can I do to the user can draw on an image and then save to database?
I want to know how can I build a Module that the user can Draw on an image and then save it to the database with Django. Like this example. Odontograma -
Simple transfer of currently logged in user to save. Django
I am looking for the simplest way to transfer the currently logged in user to my model. My model looks like this: class Person(models.Model): name = models.BooleanField(default=False) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) My forms.py class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', ) My views.py if request.method == 'POST': form = PersonForm(request.POST) if form.is_valid(): form.user = request.user.username form.save() return HttpResponseRedirect(reverse('app:home')) else: form = PersonForm() Why is not my user save method working? how is it easiest to save it correctly? -
Django Form is not valid, cannot figure out why
I just made a signup form in Django, and it is not valid for some reason that I cannot decipher. I added a field where the user could insert a registration token, in case this helps. Form: class SignupForm(UserCreationForm): token = forms.CharField() class Meta: model = User fields = ('username', 'password') Template: <form action="/register/" method="post"> {% csrf_token %} <label>Username:</label>{{ form.username }}<br> <label>Password:</label>{{ form.password }}<br> <label>Token:{{ form.token }}<br> <button type="submit">Signup</button> </form> View: def signup(request): if request.method == 'GET': form = SignupForm() return render(request, 'signup.html',{'form':form}) if request.method == 'POST' and request.user.is_authenticated == False: form = SignupForm(request.POST) if form.is_valid(): #this is where it seems to be stuck user = form.save(commit=False) username = form.cleaned_data('username') password = form.cleaned_data('password') token = form.cleaned_data('token') if SignupToken.objects.filter(token = token).exists(): user.save() db_token = RegistrationToken.objects.filter(token = token) db_token.delete() sign_in_user = authenticate(request, username, password) if sign_in_user is not None: login(request, sign_in_user) return redirect('home') else: message = 'Something went wrong.' return render(request, 'signup.html', {'message':message}) -
Is it possible to deploy a Django website using HostGator shared Linux Web Hosting?
I am looking for a solution, to deploy my Django app on my Unlimited Linux Shared Hosting Plan on Hostgator. -
400 Bad Request on application running Django Backend
I am trying to run an application that uses a Django backend/api and an React frontend. The frontend runs fine. I'm starting the backend by running the following: ./manage.py runserver 0.0.0.0:8003 And it starts without issues. I then start the frontend with npm run build When I go to the IP where I think my app is running, 123.123.12.123:8003 I see a 400 (Bad Request) error. The following errors show up in my terminal: [14/May/2019 17:45:42] "GET / HTTP/1.1" 400 26 [14/May/2019 17:45:43] "GET /favicon.ico HTTP/1.1" 400 26 every time I refresh the page. I'm new to Django so I'm hoping there is something simple that I am missing. From googling the error, I saw a lot of people saying that adding some html like <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>. There is no html in my django backend so I have nowhere to put this. -
How to get nested serializer to show all fields in parent view
I have a nested relationship between two serializers. For some reason the child serializer doesn't show all of its data. I am only seeing a type which references the class that the serializer works on, and an ID. I have tried looking this up and seen many different ways to code this relationship. Everything I have found has led me to believe that what I have should be working. I've spent a week looking into this issue and I am completely stumped. Serializers class QuotelineSerializer(serializers.ModelSerializer): # info = QuoteinfoSerializer(many=True, read_only=True) class Meta: model = Quoteline fields = ( 'lineid', 'quoteid', 'linenumber', 'lineitem', 'enabled', ... 'pricebookprice', ) class QuoteinfoSerializer(serializers.ModelSerializer): lines = QuotelineSerializer(many= True) class Meta: model = Quoteinfo fields = ( 'quoteid', 'quotenumber', 'quotecustomer', 'quotecsr', 'quoteuser', ... 'lines' ) Models class Quoteinfo(models.Model): quoteid = models.AutoField(db_column='QuoteID', primary_key=True) quotenumber = models.CharField(db_column='QuoteNumber', max_length=30) quotecustomer = models.CharField(db_column='QuoteCustomer', max_length=13) quotecsr = models.CharField(db_column='QuoteCSR', max_length=25, blank=True, null=True) salesrep = models.CharField(db_column='SalesRep', max_length=3, blank=True, null=True) ... quoted = models.CharField(db_column='Quoted', max_length=30, blank=True, null=True) market = models.CharField(db_column='Market', max_length=25, blank=True, null=True) def __str__(self): return self.quotenumber class Meta: managed = False db_table = 'QuoteInfo' class Quoteline(models.Model): # head = models.ForeignKey(Quoteinfo, related_name='lines', on_delete=models.CASCADE) lineid = models.AutoField(db_column='LineID', primary_key=True) quoteid = models.ForeignKey(Quoteinfo, related_name='lines', db_column='QuoteID', on_delete=models.CASCADE) linenumber = … -
How to create a ModelFormset to edit certain fields of an unsaved model?
In my django app I receive multiple rows of data from a server. After reception I ask the user to give each data row a name and to decide whether to sync the row in the future or not. Afterwards I save this information in the database along with the rows. This means I have the model class Row(models.Model): name = models.CharField(max_length = 191) synced = models.BooleanField(default = True) col_1 = models.CharField(max_length = 191) ... col_n = models.CharField(max_length = 191) and the form class RowForm(forms.ModelForm): class Meta: model = Row fields = ['name','synced'] In my template I want to display "name" and "synced" as form fields and "col_1",...,"col_n" as not editable data in a row. In my view: I received the data from the server and created Row model instances from it. Here is where the shit starts to get ugly. I try to define a ModelFormset. But wait a minute: I do not have a QuerySet to feed to it, since the data is not in the database yet, although it is in a model instance. Ok. Maybe I should use a regular Formset then. But wait: I do not want to feed any initial data to the Formset. … -
Calculated field based on method inside Django model
How do I automatically populate a field in my PurchaseOrder model: class PurchasedOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() @property def batch_cost(self): return self.quantity * self.product.unit_price def __str__(self): return self.product.name If I define it as a property, I won't be able to use this property to filter and stuff. I want it to be a calculated field. I tried the following but it didn't work: def calculate_batch_cost(self): return self.quantity * self.product.unit_price batch_cost = models.FloatField(default=calculate_batch_cost) I will appreciate your help <3 -
ImproperlyConfigured error on importing data from CSV file
I'm using import_export library to upload data from CSV to database, for database purpose I'm using MongoDB from django.shortcuts import render from tablib import Dataset from .resources import whsStgResource,whsMstResource ,whsInventoryResource ,stgMstResource ,stgInventoryResource ,prodMstResource from .models import whs_mst,whs_stg,stg_inventory,whs_inventory,stg_mst,prod_mst from django.http import HttpRequest,HttpResponse import io, json import csv def index(request): return render(request, "import.html") def prod_mst(request): if request.method == 'POST': prodmst_resource = prodMstResource() dataset = Dataset() new_persons = request.FILES['myfile'] new_persons2 = new_persons.read().decode('UTF-8')enter code here imported_data = dataset.load(new_persons2) result = prodmst_resource.import_data(dataset, dry_run=True) if not result.has_errors(): prodmst_resource.import_data(dataset, dry_run=False) return render(request, 'index.html') Error: ImproperlyConfigured at /prodmst/ No exception message supplied -
Django module - absent views model
I'm following the goat testing book. And I got the following issue. I'm running the django server with python manage.py runserver. Yet i'm having this error. File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/andykw/cloned_projects/unit-tests/superlists/superlists/urls.py", line 19, in <module> from lists import views ModuleNotFoundError: No module named 'lists' I know there is views.py in the app list This is what I have in urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url from lists import views urlpatterns = ['lists.views', #path('admin/', admin.site.urls), url(r'^$', views.home_page,name='home'), ] Any ideas are more than welcomde. -
What is the difference between "managed = True" and "managed = False" in django?
I wan to know the actual difference between these two code. Please anyone explain it with example so i will understand. Thanks in advance! -
Django order objects by specific related object field
In my project there is an Attraction model and an AttractionTag model related through a ForeignKey relationship. Every Attraction has the same set of AttractionTag, they differ only by the value field. Now, I want to order Attractions based on the value field of a specific AttractionTag. For example, there is an AttractionTag named 'modern' for every attraction. I want to order Attractions based on modern AttractionTag value field. I've tried attractions.order_by('-attractiontag__value') but this command order Attractions on AttractionTag in general, not based on a particular AttractionTag. Here are the models class Attraction (models.Model) : city = models.ForeignKey(City, on_delete=models.CASCADE) name=models.CharField(max_length=50, unique=True) image = models.ImageField(upload_to=attractionImagePath, null=True, blank=False) imageTop = models.ImageField(upload_to=attractionTopImagePath, null=True, blank=True) pub_date = models.DateTimeField(auto_now_add=True) class AttractionTag (models.Model): attraction=models.ForeignKey(Attraction, on_delete=models.CASCADE) name = models.CharField(max_length=50) value=models.IntegerField(default=0) How can I solve? Thank you -
Django: Proper method of totalling values from foreignkeys in related model
I am not sure what the best practice way of totalling values from foreign key integer fields in the related model is. To give an example based on the django tutorial for building a library: Say you've created your library of books and bookinstances with each book containing many real bookinstances that are in the library. You maintain an integerfield on BookInstance of number of times checked out. This way you can see how many times each specific instance has been checked out. Now you want to total all the times the instances have been checked out in the book model so you can have a quick reference for what book has been checked out the most in your library. What would be the best practice for totalling all of these values in the Book model? I currently have a working solution for my case which stores an integerfield for number of times checked out on the book model itself and then I have a function in the book model that I call from the BookInstance Model: def update_times_checked_out(self): instances = BookInstance.objects.filter(book__id = self.id) times_checked_out = 0 for i in instances: times_checked_out += i.number_of_times_checked_out self.number_of_times_checked_out = times_checked_out self.save() This works … -
How to replace/overwrite default header of EmailMultiAlternatives
Environment: Ubuntu 18.10, Python 2.7.15, Django 1.11.16 I'm trying to send an email containing an inline image. I have the following code: msg = EmailMultiAlternatives(some_subject, some_body, 'from@some-domain.com', ['to@some@domain']) img_data = open('path/to/image.png', 'rb').read() img = MIMEImage(img_data) msg.attach(img) msg.send() (I've only included the code that I think is relevant but I can add more on demand.) The above properly works and the image is properly displayed on most of the email clients (about 7 of them, both mobile, desktop or webmail ones) that I tested on, with two exceptions: Mozilla Thunderbird 60 and some macOS native email client. On Thunderbird the image is not displayed inline but at the very end of the message. On the macOS client, the image is displayed inline but additionally it is also displayed at the very end of the message. I composed and sent a test message from another email client, containing an inline image which was properly displayed on both Thunderbird and macOS. I compared the headers of this message with the headers of the message generated by my code. I noticed that the faulty message has the 'Content-Type' set to 'multipart/mixed' while the properly displayed message had the same header set to 'multipart/related'. I … -
How to fix makemigrations after upgrade to Wagtail 2.5 get ImportError
I have upgraded from Wagtail 1.6.1 to 2.5 and I am trying to makemigrations, but I receive this error: ImportError: cannot import name 'TranslationMixin' When I try to add the TranslationMixin to this block of code in my model: class Image(TranslationMixin, models.Model): image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) caption = models.CharField(max_length=255, blank=True) -
Populate map with user address input
I'm trying to complete a project where the user creates an event. One of the model fields for the event is the address of it. Here is the relevant part of my Models.py page. from django.db import models from django.contrib.auth import get_user_model class Event(models.Model): name = models.CharField(max_length=40) address = models.CharField(max_length=200) notes = models.CharField(max_length=900) object_list = Event.objects.all() class Comment(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='comments') comment = models.CharField(max_length=280) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) I want to take the text from the address field from the Event model and enter in a map so the user can see where the event is located. I then want to create a template where the events are listed with a clickable map thumbnail with a flag or something to denote where the event is located on the map. Please let me know if this is something that can be done or if you need more detail. Thanks.