Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: how do i get values from <div> of HTML into django views and use the value?
so I have used leaflet and Javascript for rendering maps and calculate distance. the calculated distance is passed to and I need to extract the value and use it in django views to sort the object by distance in another page. How do I do it? -
TypeError: type CombinedExpression doesn't define __round__ method
I'm using the ipython (Python 3.7) console in PyCharm. I'm trying got run a Django ORM query where I want to do some date math specifically calculating number of seconds and comparing that to another field. I tried Article.objects.filter(article_stat__elapsed_time_in_seconds=(round(datetime.now(timezone.utc) - F("created_on")) / 300) * 300) but I'm getting the following error Traceback (most recent call last): File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3267, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-18-607b95229a28>", line 1, in <module> Article.objects.filter(article_stat__elapsed_time_in_seconds=(round(datetime.now(timezone.utc) - F("created_on")) / 300) * 300) TypeError: type CombinedExpression doesn't define __round__ method Here is the model in question ... class Article(models.Model): ... created_on = models.DateTimeField(default=datetime.now) How do I overcome this "TypeError: type CombinedExpression doesn't define round method" error? -
Manager isn't accessible via __ instances when getting model objects
I'm just transitioning to python. I just cant populate my html list from data in models. here's my model just to show details but i think there's nothing wrong here from django.db import models class Student(models.Model): student_id = models.CharField(max_length=10, primary_key = True) first_name = models.CharField(max_length = 30) middle_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30) course = models.CharField(max_length = 50) year = models.IntegerField(default=1) section = models.CharField(max_length=1) Here is the view and the html file that I'm not sure where I messed up view: from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import Student @login_required def home(request): student = Student return render(request, 'studentapp/studenthome.html', { 'student':student, }) studenthome.hmtl {% extends 'base.html' %} {% block content %} <h2>Student Home</h2> <ul> {% for students in student.objects.all %} <li>{{students.first_name }} {{students.middle_name}} {{ students.last_name }}</li> {% endfor %} </ul> {% endblock %} I think the error is related to the for statement here in html file but I really have no idea Error: Manager isn't accessible via Student instances -
Compare naive time with aware datetime object in Django
One my models has DateTimeField which get assigned at some point in the flow of the app. class SomeModelWithAwareDateTimeField(models.Model): timestamp = models.DateTimeField(...) Yet another model has unaware TimeField which represents time slot, unrelated to date or specific day, just plain time like 17:00. class SomeModelWithNaiveTimeField(models.Model): time = models.TimeField(...) At some point I need to filter SomeModelWithAwareDateTimeField objects by time stored in time field of SomeModelWithNaiveTimeField object. SomeModelWithAwareDateTimeField.objects.filter( timestamp__time=instance_of_some_model_with_naive_time_field.time ) But because I'm using time zone support USE_TZ = True values mismatch, although both represent the same time. How do I convert time field to aware time object and compare two? -
Django: Searching with __icontains Across All Fields Produces Duplicates
I have a Django model called Books(models.Model) that has a variety of fields including author, title, and year created. I want to filter this list across all fields of the Book model. For example, if I search for "Winnie," I want all Book instances with "Winnie" in the title, author, or year created to come up, but do NOT want to same instance of a model to come up. For instance, if "Winnie" is in the title AND author of a specific instance, I only want that instance to appear once. I have tried using the following code to accomplish this: books = Books.objects.filter(Q(title__icontains=search_query) | Q(author__icontains=search_query) | Q(year_created__icontains(search_query)) where search_query is a variable that represents the search query. However, I am getting duplicate results as explained earlier. How do I prevent these duplicate results? Any help is greatly appreciated! Thanks! -
Is Django Channels supported in Google App Engine?
I saw that now GAE supports WebSocket... I would know if this include Django Channels (I use the standard GAE, not Flex one). Fonts (scroll down the page): https://issuetracker.google.com/issues/35886348 -
DRF serialize and save model with user FK
models.py class UserContentItem(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) views.py class UserContentItemView(APIView): permission_classes = (permissions.IsAuthenticatedOrReadOnly, ) def post(self, request, format=None): data = request.data data['owner'] = request.user.id serializer = UserContentItemSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class UserContentItemSerializer(serializers.ModelSerializer): class Meta: model = UserContentItem fields = ('id', 'owner', 'title', 'created_date') I am building an API with Django Rest Framework and simple jwt. I want to allow authenticated users to POST a new UserContentItem that has a FK dependency on the User but the User is not part of the POST payload. The only way I've been able to figure out how to do this is as above, adding the request.user.id to the request data before passing it to the serializer. Is there a better way to serialize the UserContentItem and achieve the same goal? -
Getting an error while trying to perform the python manage.py migrate command
When I am trying to run the python manage.py migrate , I am getting the attached error. raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ORA-00907: missing right parenthesis) I am using the below packages cx_oracle 6.3.1 django 2.1.5 backend Oracle 10g XE DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xe', 'USER': 'django', 'PASSWORD': 'oracle', 'HOST': 'localhost', 'PORT': '1521', } } enter image description here -
Making a button group dynamic
I have data coming from a 3rd part API which I can parse using JQuery into multiple arrays which I want to display in a chart. I have taken this out to simplify the code and I'm using two fixed arrays newData1 and newData2 I have successfully created buttons that switch between the two data arrays and change the chart so the chart is dynamic and changes on the button click What I can't work out is how to make the number of buttons dynamic and populate them from a list - the length of which could vary and is taken from the array called button_list The function printBn does create a dynamic list of buttons, but I doesn't appears as a button group and take the Bootstrap styling that I've tried to apply like this <div class="btn-group-vertical" role="group" aria-label="First group"> <button id="btn1" type="button" class="btn btn-secondary">1</button> <button id="btn2" type="button" class="btn btn-secondary">2</button> </div> I basically want a way to make that Bootstrap html dynamic charts.html {% extends 'base.html' %} <script> {% block jquery %} var endpoint = '/api/data/'; var newData1 = [0.9, 0.9, 0.9]; var newData2 = [0.2, 0.2, 0.2]; var data = []; var button_list = ['Test1', 'Test2', 'Test3', 'Test4']; … -
NameError: name 'F' is not defined in Django ORM query
I'm using the ipython (Python 3.7) console in PyCharm. I'm trying got run a Django ORM query Article.objects.filter((round(datetime.now(timezone.utc) - F("created_on")) / 300) * 300) but I'm getting the following error Traceback (most recent call last): File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3267, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-12-53618885441a>", line 1, in <module> Article.objects.filter((round(datetime.now(timezone.utc) - F("created_on")) / 300) * 300) NameError: name 'F' is not defined I thought "F" was the way to reference a field in my model in an expression but I get the error above. My Article model contains the field as below ... class Article(models.Model): ... created_on = models.DateTimeField(default=datetime.now) -
How to run JS inside an if block in django templates?
I want to run an alert, but only if there are messages, and with all the messages in a single alert. I'm trying this way: {% if messages%} <script type = "text / javascript"> alert {% for message in messages%} {{message}} {% endfor%} ); </ script> {% endif%} But the alert does not run on the page, and when I inspect the element, this appears: <script type = "text / javascript"> alert Wellcome, marcosr00t ); </ script> obs: the script is inside the main > section element -
Multiple periodic long running tasks
I have multiple websocket feeds which i'm trying to run continuously. My idea was to use celery beat to run these automatically with a task lock to not run multiple instances. I've scheduled the task to run every 1 second incase they die so they automatically restart with little interruption. Currently I can only get one running at a time. Where am I going wrong or is there a better way to approach this? @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(1.0, task1.s(), name='task1') sender.add_periodic_task(1.0, task2.s(), name='task2') LOCK_EXPIRE = 60 * 10 @contextmanager def task_lock(lock_id, oid): timeout_at = monotonic() + LOCK_EXPIRE - 3 status = cache.add(lock_id, oid, LOCK_EXPIRE) try: yield status finally: if monotonic() < timeout_at and status: cache.delete(lock_id) @app.task(bind=True) def task1(self): with task_lock("task1-id", self.app.oid) as acquired: if acquired: start_socket("socket1") @app.task(bind=True) def task2(self): with task_lock("task2-id", self.app.oid) as acquired: if acquired: start_socket("socket2") -
Django-Oscar: Adding slugs to url
I would like to be able to add a the following: [(?P<slug>[-\w]+)] after /dashboard/' between that and the rest of any possible url that comes after, i.e. '/dashboard/ (?P<slug>[-\w]+) /catalogue/. The point of this would be to make it 'partner-specific' for my particular project. How would I go about doing this? I currently am working directly with Oscar code for several reasons, meaning that I do not have to 'fork' any apps - I just change the Oscar code within my project. The strategy I am trying to accomplish this URL-change is to go into app.py and adding it there after 'dashboard', or going into dashboard/app.py and adding it before each url defined there. Whenever I change I keep getting 'NoReverseMatch at ---' and errors like: Reverse for 'MY-URL-IS-HERE' with no arguments not found. 1 pattern(s) tried: ['dashboard/(?P<slug>[-\\w]+)/logout/$'] I am familiar with this error, but now seem unable to ever locate the exact location of the error message. And whenever I do get the page to load (was able to when adding it before 'reviews'), I still get an error something like the following in the terminal: Invalid URL name dashboard:reviews-list Traceback (most recent call last): File "/Users/myname/Desktop/Developer/wybe-all/wybe/apps/oscar/dashboard/nav.py", line 83, … -
How can I set specific HTML-tags with Jinja as safe / unsafe? [duplicate]
This question already has an answer here: Sanitising user input using Python 7 answers I'm trying to replace specific text in user generated content with fully working HTML using Jinja2. I'm using this code: {{content | replace("\n", "<br/>") | safe}} The problem is that the user can now submit any HTML he want. So how can I set only specific HTML-tags with Jinja as safe / unsafe? -
Django Abstract Class change behaviour according to actual class
I think following code explains what I'm trying to do from django.db import models class MyBaseClass(models.Model): type = models.IntegerField() class Meta: abstract = True def save(self, *args, **kwargs): self.type = #What Should I write here?# self.type = self.class.type ? super().save(*args, **kwargs) class Model1(MyBaseClass): TYPE = 1 class Model2(MyBaseClass): TYPE = 2 I want to make sure following assertions work: instance1 = Model1.objects.create() assert(instance1.type, 1) instance2 = Model2.objects.create() assert(instance1.type, 2) How can I make this work? Thanks. -
Checkbox input in form disappearing after submit
Created a form that enters boolean values on submit using checkbox inputs. When the form is submitted and the page reloads, the checkbox form inputs disappear. This is on Django and I have tried changing the views function to potentially keep it there, but I haven't found a solution. HTML <form action="{% url 'student:account_notifications' %}" method="POST" autocomplete="off"> {% csrf_token %} <div class="email"> <p>Email notifications</p> </div> <!-- Check Boxes --> <div class="checkbox"> {{ form.schedule }} <label>When you schedule a lesson</label> </div> <div class="checkbox"> {{ form.cancel }} <label>When a lesson is cancelled</label> </div> <div class="checkbox"> {{ form.day_reminder }} <label>24 hour reminder before your lesson</label> </div> <div class="checkbox"> {{ form.half_hour_reminder }} <label>30 minute reminder before your lesson</label> </div> <div class="bottom"> <button type="submit" name="submit" class="btn blue_button">Save</button> </div> forms.py class ChangeNotificationsForm(forms.ModelForm): schedule = forms.BooleanField(widget=forms.CheckboxInput(attrs={'checked' : 'checked'}), required=False) cancel = forms.BooleanField(widget=forms.CheckboxInput(attrs={'checked' : 'checked'}), required=False) day_reminder = forms.BooleanField(widget=forms.CheckboxInput(attrs={'checked' : 'checked'}), required=False) half_hour_reminder = forms.BooleanField(widget=forms.CheckboxInput(attrs={'checked' : 'checked'}), required=False) class Meta: model = Notifications fields = ('schedule', 'cancel', 'day_reminder', 'half_hour_reminder') views.py def account_notifications(request): if request.method == 'POST': form = ChangeNotificationsForm(request.POST) if form.is_valid(): schedule = request.POST.get('schedule', '') == 'on' cancel = request.POST.get('cancel', '') == 'on' day_reminder = request.POST.get('day_reminder', '') == 'on' half_hour_reminder = request.POST.get('half_hour_reminder', '') == 'on' notifications_obj = Notifications(schedule … -
Dependant fields in Django admin
I have a model which must be able to save information about when/what actions must be executed by a task (the task-related stuff are out of the scope of this question, so I won't get into details about that). The actions are divided into at least 3 sections. The first section is "when" (before or after the task has been executed), so that should show up in the django admin like a dropdown (this one is easy). The second section is what action should be executed (perform a click, transform a text, get regex match, etc...), which should also show up as a dropdown in django's admin (this one is easy too). Here comes the difficult part. Depending on the selection of the second section, I must show another input field(s) of some sort. For example, if I select perform a click in the second section, the third section would show a text field in which I should type the CSS selector for the element I want the task to click. But if I select transform a text in the second section, then the third section should show me a dropdown with several options such as uppercase, lowercase, append, etc... … -
Loading Models Progressively - Django
I have a web application which uses Django as the backend and HTML, CSS, and JQuery for the front end. One of the models in the backend is Books(models.Model) which has over a thousand of instances. I want to load these instances on to the page to display to users and have a searching functionality which would allow them to search the books by author, title, etc. The problem is that in order to load all these books onto the page, it takes a LONG time. I would like to be able to do this progressively and add new books once they reach the end of the books currently shown. How can this be accomplished? -
Reverse for 'edit_team' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['club_home/edit_team/(?P<pk>[0-9]+)/$']
Receiving the above error when trying to create a page to update my model using a serializer. Unable to use pk in edit_team view. Any ideas where I am going wrong? Delete button is working fine with the pk not sure why the update is not. urls.py path('teams/', views.TeamInfo.as_view(), name='teams'), path('delete_team/<int:pk>/', views.delete_team, name='delete_team'), path('edit_team/<int:pk>/', views.edit_team, name='edit_team'), teams.html <div class="team"> <h3>Team Details</h3> <p> {% csrf_token %} {% for info in teams %} <li>{{ info.club_id }}</li> <li>{{ info.team_name }}</li> <li>{{ info.manager_name }}</li> <form action="{% url 'clubs:delete_team' info.pk %}"> <input type="submit" value="Delete"> </form> <form action="{% url 'clubs:edit_team' info.pk %}"> <input type="submit" value="Edit"> edit_team.html {% extends 'club_main_page.html' %} {% load rest_framework %} {% load staticfiles %} {% block body_block %} <div class="editteam"> <h3>Edit Team</h3> <form action="{% url 'clubs:edit_team' pk=instance.pk %}" method="POST"> {% csrf_token %} {% render_form serializer %} <input type="submit" name="" value="Update"> </form> </div> {% endblock %} views.py def delete_team(request, pk): team = Team.objects.filter(pk=pk) team.delete() return redirect('clubs:teams') def edit_team(request, pk): instance = Team.objects.filter(pk=pk) if request.method == 'POST': serializer = TeamSerializer(request.POST, instance=instance) if serializer.is_valid(): serializer.save() return redirect('/') else: return redirect('/') else: serializer = TeamSerializer(instance=instance) return render(request, 'edit_team.html', {'serializer': serializer}) Trackback: \clubkit\clubs\views.py in edit_pitch return render(request, 'edit_pitch.html', {'serializer': serializer}) -
when i "import oss2" to control the aliyun's oss bukect,my django go wrong
It was all right the other day, but suddenly something went wrong today. Looking at the error message, we found that there was a problem with this oss2. His error message was as follows, saying that the module "_is_immutable" could not be found. ImportError: cannot import name '_is_immutable' from 'Crypto.Util.py3compat' (/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/Crypto/Util/py3compat.py) -
Django onetoone relationship with User not working with query
My model is like this class Profile(models.Model): user = models.OneToOneField(User,default=None,null=True,on_delete=models.CASCADE) name = models.CharField(max_length=50,null=True) i am trying to get through models using shell but getting the empty query. I tried this >>> u1=User.objects.get(username='gautam') >>>u1 <User: gautam> >>> Profile.objects.get(user=u1) Traceback (most recent call last): File "/usr/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/home/gautam/.local/lib/python3.6/site- packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/gautam/.local/lib/python3.6/site- packages/django/db/models/query.py", line 399, in get self.model._meta.object_name homes_login.models.DoesNotExist: Profile matching query does not exist. I am tring to get the user for that profile. -
How to set a default value for a foreign key attribute for a table that does not exists yet in Django?
I have a pre-existing Django Model class, in which I need to add a one-to one relationship with another model class that is not created yet in the DB yet. I'm planning to fill the new model with some default values by cakking function in urls.py, but I'm not sure about the id of those values that'll be generated in the DB to assign it as a default value to the foreign key. Is it a good idea if I hardcode the value 1 as default assuming that the record A for the new model will have a PK value of 1? Is it a better approach to this? -
How to print dict data in html if i submit form using ajax
i am new in django i am try to create a short url website and i short the url without page refresh using ajax and i create a unique url in my view.py but i am not knoe how to print the create url using jsonresponce please tell me how i do it this is my index.html <form method="POST" id="shorten" class="form-inline">{% csrf_token %} <div class="form-group"> <input type="url" value="{{ url }}" name="url" placeholder="Your URL Here" required="required" class="form-control input-lg" id="url"/> <button id="submit" class="btn-captcha" style="display: flex;" type="submit"><img src={% static "img/right-arrow.png" %} alt=""/></button> <div> {{url}}<div> </div> </form> this is my ajax code for form submit <script> $(document).on('submit','#shorten',function(e){ e.preventDefault(); $.ajax({ type:'POST', url: '/shorturl/', data:{ url:$('#url').val(), csrfmiddlewaretoken : $('input[name=csrfmiddlewaretoken]').val() }, success:function(){ alert("ok") } }); }); </script> this is my views.py def shorturl(request): if request.method == 'POST': url = request.POST.get('url') obj = userurltable(url = url) obj.save() obj2 = userurltable.objects.last() url_id = obj2.id code = short_url.encode_url(url_id) shortened_url = settings.BASEURL + code dic = {"url": shortened_url } # i want to send this dict to my html page and print this url in html i am note use render because i am submit the form using ajax so all is in front of you please tell mi how i … -
Bad Coding Practices related to LFI and RFI vulnerability
Can anyone help me with bad and best practices in django framework related to LFI(local file inclusion) and RFI(remote file inclusion) vulnerabilities. If possible, help me with the code. -
pipenv on production workaround with user, is it viable?
I have been experiencing this issue here when I am trying to set pipenv on EC2.t2 free tier for production with Django. On the solution listed on that same post it says: it is important to note that pipenv will likely not be able to be installed at the global level due to the pip conflict. You can install pipenv at the user level: pip install --user pipenv My question is, since this is production mode, wouldn't this be bringing me problems later on since I am installing my packages with some random user's privileges? Anyone has any video of using pipenv in production?