Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models TextField/CharField: Remove null characters
I have a view that takes, in many parts, data from a, let's say, untrusted source, and I want to save the data in a Django model's TextField. The input may have null characters, and, if I understand correctly, Postgres (the backend of my project) prohibits saving null characters in the database. I could use str.replace to replace the null characters, but I would have to riddle my codebase with str.replace, since I have many points where I create models out of the untrusted data. Is there a way to force the cleaning of the data in the model level? I mean, so that I could do my_model.save() and in a unique place in my code have str.replace, instead of having it in all the places I have a TextField. -
Django - Limit object level access based on foreign key
I have a django data model that roughly looks like class Project: ... owner = FK(User) class User: ... project = FK(Project) class Data: .... project = FK(Project) And I'd like to enforce that a User can only interact (view/delete whatever) with Data if his he has a FK to the Project that the Data does. I can query this at every access point but I think that's error prone, and am also concerned about performance penalty of frequent joins. Are their other alternatives ? Thanks -
How can I turn an AngularJS template into a string?
I want to pass my variables into that template, let it render, and then get the resulting HTML as a string. How can I do that in AngularJS? Is there a similar function to the render_to_string() function in Django? The purpose is to make an API request to a service that sends emails and needs the html to be sent as a parameter of the request. Thanks a lot in advance! -
How to set instance variables in a class based view?
I want to check if a user is in a specific group on initilisation of the class based view. Then use that variable in a number of methods like get_form()and get_context_data() However I get an error: File "/projects/hr_project/entries/views.py", line 117, in get_form_class if self.is_manager: AttributeError: 'EntryCreateView' object has no attribute 'is_manager' Here is the methods in the class based view: def dispatch(self, request, *args, **kwargs): self.is_manager = False manager_group = Group.objects.get(name='Managers') if manager_group in request.user.groups.all(): self.is_manager = True def get_form_class(self): if self.is_manager: return ManagerEntryForm return UserEntryForm -
Django Foreign Key Not Rendering Related Model Data In Template
New to coding so apologies if this has been covered. Spent the last few evenings on Django's docs, YouTube, Google and here trying all kinds of ways to fix this. I have a model Route which is related to Driver and I am trying to display all the routes with the relevant drivers associated with that route on my template. However at the moment all I can get is the data from the Route model, not the associated Driver. Would appreciate any help on this as I'm struggling to get my head around it! Models.py class Driver(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) first_name = models.CharField(max_length=120, blank=True, null=True) last_name = models.CharField(max_length=120, blank=True, null=True) tel = models.CharField(max_length=120, blank=True, null=True) slug = models.SlugField(max_length=120, unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.first_name def save(self, *args, **kwargs): self.slug = slugify(self.first_name) super(Driver, self).save(*args, **kwargs) class Route(models.Model): leave_from = models.CharField(max_length=120, blank=True, null=True) destination = models.CharField(max_length=120, blank=True, null=True) date = models.DateField(auto_now_add=False, auto_now=False) time = models.TimeField(auto_now_add=False, auto_now=False) drivers = models.ForeignKey(Driver, on_delete=models.CASCADE) def __str__(self): return self.leave_from Views.py def drivers(request): qs = Route.objects.all().select_related() context = { "qs": qs, } return render(request, 'drivers.html', context) Template {% for instance in qs %} <p>{{ instance.user }} <br> {{ instance.first_name }} … -
Django Notifications when new alert fired in alertmanager
I have an application developed using django framework which displays alertmanager alerts in different format.I have a requirement in which i need to send a notification message to the web application when new alerts is being fired in alertmanager using django framework.I don't know how to implement that.Main doubt is, how to check in alertmanager when new alerts is fired.Kindly help me out in this.. -
Log long-running queries in django
We're running postgres and sometimes the django ORM generates long-running queries. You can log queries in postgres as detailed here. Any query generated by the log can be difficult to tie back to actual code that generated it. Is there a good way of tying a query to the actual code? -
ModelChoiceField - вопрос по required
Please explain , I have model = TestModel , which has attribute testatribute = models.CharField(blank=True , null=True,choices=test_choice, max_length=15) I Have been using this Form: tarrif = forms.ModelChoiceField(required=....) Task : filter form so that the value in the attribute testatribute was available in the form. TestModel.objects.all() - Cannot using because models has other attributes -
Django - How to pull a logged in users data from a database table?
I am relatively new to Django, and web development in general. Basically, I want to pull a logged in users data from a database table so he can view/edit it on a 'My profile' page. I'm guessing the best way to do this would be to call the logged in users 'id', then somehow use it to call the row in the database table I want? This is how far I have got, but I don't want the user's 'id' in the url, I want the users 'row id' in the database table: urls.py url(r'^my-profile/(?P<id>[0-9]+)', my_profile, name="my_profile"), views.py user = request.user template <a href="{% url 'my_profile' id=user.id %}">My profile</a> Any help would be much appreciated! -
Django - How to run a function inside a constructor?
As far as I've read, overriding the init function is not recommended in Django. Then how can I assign value to "hashed" and "salt"? They will not have the value of the original text, there are functions named def createSalt(self): and def createHash(self, salt, password): that will take the original text and convert it to something different. I tried this in model class but it didn't work: (it probably looks stupid ) salt = models.TextField(createSalt()) or salt = models.TextField(createSalt(self)) Another suggestion was to define a new function named create and use it like a constructor. But then it's not really a constructor, is it? Here is my model: class User(models.Model): username = db.Column(db.String(100), primary_key=True) hashed = models.TextField() salt = models.TextField() -
Insert count objects fields in Array Django Rest Framework
I get a problem in Django Rest Framework. class FeedDetailSerializer(ModelSerializer): user = UserFeedSerializer(read_only=True) comment_count = SerializerMethodField(default=0) comment_list = CommentFeedSerializer(many=True, read_only=True) class Meta: model = Feed fields = [ 'id', 'comment_count', 'comment_list', ] def get_comment_count(self, obj): comment_count = Comment.objects.filter(feed=obj.id, parent__isnull=True).count() return comment_count This is the CommentFeedSerializer I've created: class CommentFeedSerializer(ModelSerializer): url = comment_detail_url class Meta: model = Comment fields = [ 'url', 'id', 'comment', 'posted_on', ] With this Serializer I've done, API will render like this: "comment_count": 2, "comment_list": [ { "url": "http://localhost:8000/api/v1/comments/2/", "id": 2, "comment": "haha", "reply_count": 0, "posted_on": "2017-11-24T10:23:28.353000Z" }, { "url": "http://localhost:8000/api/v1/comments/1/", "id": 1, "comment": "Good", "reply_count": 1, "posted_on": "2017-11-24T09:54:48.680000Z" } ] But this is very hard to manage. So I want to put comment_count into comment_list: commentlist [comment_count:1, {}] How can I do that? -
Divide multipolygon Area into subarea
I am working on an application, where I have shapes (.shp) files, I have read those shapes file into my Postgres database and show those shapes file coordinates over the Google Map. Now I'm having a use-case, I need to divide these LGA (Local Governance Area) into sub area (like divide an LGA into 10km2 sub-area). Can anyone have any idea how can I do this using python/Django/GeoDjango? suggestions are welcome. Thanks -
How can I use the forloop.counter0 as a key in Django Template
I use a custom Widget to modify the context for the widget template (add more information). Context: 'selected': [[3, 9], [3, 4, 7, 6]], 'depth_levels': {0: [{'name': 'Category A', 'value': 3, 'depth': 0, 'parent_id': None, 'children': [4, 9]}, {'name': 'Category B', 'value': 8, 'depth': 0, 'parent_id': None, 'children': []}], 1: [{'name': 'Category A_1', 'value': 4, 'depth': 1, 'parent_id': 3, 'children': [5, 7]} {% for path in widget.selected %} {% for selected in path %} {% for level in widget.depth_levels.forloop.counter0 %} {{ level }} {% endfor %} {% endfor %} {% endfor %} First I cycle thru the selected(path) and the internal arrays(selected). I want to use the {{forloop.counter0}} as a key for depth_levels. The issue: {{widget.depth_levels.forloop.counter0}} doesn't return anything. If I use the key 'manually'{{widget.depth_levels.0}} is working returning the value, the array of dictionaries. My end goal is to access the name, value in the dictionaries that are in the array. -
I get a csrf error when saving db from django's admin
MIDDLEWARE_CLASSES = ( # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) This is my settins.py code. I have no problem logging in and viewing the db. If I press the save button to modify or add a db, I get a 403 error. -
(Django) ORM in airflow - is it possible?
How to work with Django models inside Airflow tasks? According to official Airflow documentation, Airflow provides hooks for interaction with databases (like MySqlHook / PostgresHook / etc) that can be later used in Operators for row query execution. Attaching the core code fragments: Copy from https://airflow.apache.org/_modules/mysql_hook.html class MySqlHook(DbApiHook): conn_name_attr = 'mysql_conn_id' default_conn_name = 'mysql_default' supports_autocommit = True def get_conn(self): """ Returns a mysql connection object """ conn = self.get_connection(self.mysql_conn_id) conn_config = { "user": conn.login, "passwd": conn.password or '' } conn_config["host"] = conn.host or 'localhost' conn_config["db"] = conn.schema or '' conn = MySQLdb.connect(**conn_config) return conn Copy from https://airflow.apache.org/_modules/mysql_operator.html class MySqlOperator(BaseOperator): @apply_defaults def __init__( self, sql, mysql_conn_id='mysql_default', parameters=None, autocommit=False, *args, **kwargs): super(MySqlOperator, self).__init__(*args, **kwargs) self.mysql_conn_id = mysql_conn_id self.sql = sql self.autocommit = autocommit self.parameters = parameters def execute(self, context): logging.info('Executing: ' + str(self.sql)) hook = MySqlHook(mysql_conn_id=self.mysql_conn_id) hook.run( self.sql, autocommit=self.autocommit, parameters=self.parameters) As we can see Hook incapsulates the connection configuration while Operator provides ability to execute custom queries. The problem: It's very convenient to use different ORM for fetching and processing database objects instead of raw SQL for the following reasons: In straightforward cases, ORM can be a much more convenient solution, see ORM definitions. Assume that there is already established systems like … -
Display Django DateTime Field with strftime() method
I am trying to format the string of a DateTimeField contained in one of my models. I am using this method inside the model: def HTMLDisplayTime(self): time = self.time.date.strftime(%a %H:%M %d/%m/%y) return time Where "self.time" refers to the DateTimeField in question. I have tried several variations, omitting some items, with and without .date preceding the .strftime method, and have imported both import datetime and from datetime import datetime. -
How to pass key not value with jquery autocomplete
This is my jquery file.. usastates.js var usastates = { "AL": "Alabama", "AK": "Alaska", "AS": "American Samoa", "AZ": "Arizona", "CA": "California", "CO": "Colorado", } & this is my search form. <form action="/search" method="GET"> <div class="col-lg-4 col-sm-4 search-col relative"> <input class="form-control has-icon" type="text" name="=state" id="autocomplete-ajax" placeholder="Location ..." value=""> </form> I have a button to send this data. Currently in the URL I am sending the full statename i.e 'http:localhost:8000/search?state=ALABAMA' I would like to change this to send just 'AL' rather than 'ALABAMA'. Any thoughts? thanks -
Django - Submitting form with multiple inputs for same field
Forewarning: I'm very new to Django (and web development, in general). I'm using Django to host a web-based UI that will take user input from a short survey, feed it through some analyses that I've developed in Python, and then present the visual output of these analyses in the UI. My survey consists of 10 questions asking a user how much they agree with a a specific topic. Example of UI for survey: Example of UI input screen For models.py, I have 2 fields: Question & Choice class Question(models.Model): question_text = models.CharField(max_length=200) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text I am wanting to have a user select their response to all 10 questions, and then click submit to submit all responses at once, but I'm having trouble with how that would be handled in Django. Here is the html form that I'm using, but this code snippet places a "submit" button after each question, and only allows for a single submission at a time. NOTE: The code below is creating a question-specific form for each iteration. {% for question in latest_question_list %} <form action="{% url 'polls:vote' question.id … -
iterate specific dictinary values in django template
I new to django when i receive a associative array namely dictionaries in python which as follows "receivable_aging": { "age5": 235114.91999999998, "age4": 235114.91999999998, "age3": 0, "age2": 0, "age1": 0 } I want to print age1 to age4 in ascending order. how can i achieve this without if or minimal steps. -
Bigchaindb program running
When I am trying to run the program in https://docs.bigchaindb.com/projects/py-driver/en/latest/usage.html I got the following error. please help me to solve the query. Traceback (most recent call last): File "bdb.py", line 1, in from bigchaindb_driver import BigchainDB File "/usr/local/lib/python3.5/dist-packages/bigchaindb_driver/init.py", line 1, in from .driver import BigchainDB # noqa File "/usr/local/lib/python3.5/dist-packages/bigchaindb_driver/driver.py", line 16 def init(self, *nodes, transport_class=Transport, headers=None): ^ SyntaxError: invalid syntax -
How to install JSONFields properly?
I just wanted to upload my django project on digitalocean, but ran into multiple problems, of which I can not solve the last one. I am using a restframework. After getting an error, that there is No module named rest_framework.views I installed but therefore get the error: AttributeError at / 'module' object has no attribute 'JSONField' Simply installing JSONField does not change anything. I think it still has to do with the restframework module. /usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py in <module> ModelSerializer.serializer_field_mapping[postgres_fields.JSONField] = JSONField I have been trying to solve it for hours already but nothing helps... Has someone had the same problem or knows how to fix it? Thanks a lot and kind regards -
Does django_celery_beat support crontab schedules with multiple minutes/hours?
I am using django-celery (https://pypi.python.org/pypi/django-celery/) to store celery beat (Periodic Task) schedules in the DB. But it doesn't support celery beyond version 3.1.25. I want to move to celery 4.1.0 and so I was looking at moving to django_celery_beat (https://pypi.python.org/pypi/django_celery_beat) for db based schedules. I was able to successfully migrate the table structures along with data. However, I see that django_clery_beat does not support crontab schedules with multiple minutes and hours which djcelery supported. For example, consider this crontab schedule - 15,30,45 0,1 * * * The task will run everyday at 12:15, 12:30, 12:45, 1:15, 1:30, 1:45. This used to work in django-celery. But in django_clery_beat, it only seems to execute at 12:15 (first one). Old setup - Django==1.10, celery==3.1.24, django-celery==3.1.17 New setup - Django==1.11.7, celery==4.1.0, django-celery-beat==1.1.0 Can anyone confirm if that support for such crontab schedules has been dropped in django_celery_beat? If it is supposed to work, is it an issue with celery or django_celery_beat? Thanks -
Eoor given In Django template loop for javascript
I am tried store value in javascript from django loop. But when I load the browser it showing error"mxwaterlv is not defined". But I already defined the variable. here is my code. {% if all_FloodLocs %} {% for map in all_FloodLocsMAX %} // max foolf can be location using twiiter API var confirmaddress ="{{ map.LocName }}"; var twicount ={{map.count}}; {% endfor %} {% else %} {% endif %} {% if all_waterLevels %} {% for waterLevel in all_waterLevelsMAX %} // max foolf can be location using twiiter API var mxwaterlv ={{ waterLevel.W_height }}; {% endfor %} {% else %} {% endif %} views.py def compare(request): end_date = timezone.localtime(timezone.now()).replace(tzinfo=pytz.timezone('America/Guatemala')) start_date = end_date + relativedelta(hours=-83) all_waterLevels = waterLevel.objects.filter(date__range=(start_date, end_date))[:5] all_waterLevelsMAX = waterLevel.objects.filter(date__range=(start_date, end_date))[:1] all_FloodLocs = Map.objects.values('LocName').annotate(count=Count('LocName')).order_by('-count')[:5] all_FloodLocsMAX = Map.objects.values('LocName').annotate(count=Count('LocName')).order_by('-count')[:1] context = {'all_waterLevels': all_waterLevels, 'all_FloodLocs' : all_FloodLocs, 'all_FloodLocsMAX':all_FloodLocsMAX, } return render(request, 'Home/compare.html', context) please help me to solve this. var confirmaddress and var twicount working perfectly -
Сheck user permissions not working in template after AJAX refresh?
I have strange behavior. Can someone say whats wrong? In template I show list of objects as in the picture below. When user add/edit/delete any data by form I update list of users by AJAX. Problem is that after refresh by AJAX buttons disappear in list. It seems like {% if perms.foo.do_something %} dont work with AJAX. Whats wrong and how to fix this problem? P.S. In the same time if I refresh page by browser {% if perms.foo.do_something %} works perfect. Show permissions correct. I am confused. At start: After refresh list by AJAX: Below example of code: javascript: // Submit Form $(function () { var saveForm = function () { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#users").html(data.html_users); $("#user-modal").modal("hide"); } else { $("#user-modal .modal-content").html(data.html_form); } } }); return false; }; // Update User Data $("#users").on("click", ".user-edit-btn", loadForm); $("#user-modal").on("submit", ".user-edit-form", saveForm); }); views.py: class UserEditView(UpdateView): template_name = 'users/edit_user.html' form_class = UserEditForm model = User permission_required = ('auth.change_user') def form_valid(self, form): form.save() data = dict() data['form_is_valid'] = True context = {'users': User.objects.order_by('username')} data['html_users'] = render_to_string('users/users.html', context) return JsonResponse(data) *** users.html: {% for user in users %} <div … -
How Can I get the data from Django JSONField
I am having JSONField in my model class Activity(models.Model): extra = JSONField(null=True, blank=True) And this is my serializer class. There is a field run_id in extra. How can I take run_id in Serializer? class ActivitySerializer(serializers.ModelSerializer): extra = serializers.CharField(read_only=True) def get_extra(self, model): return model.extra['run_id'] I tried this, But not Working