Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing selected parameters from form with three choicefields to urls or view
I am new to Django and working on getting my first application running. The Quiz model encompasses everything and each entry is unique with combination of grade,subject and year fields. I have SearchForm form to let users select and search in index page. I want the user to first select grade from available levels then select subject from available types which are dependent on the level previously selected, and lastly year from years, also dependent on type. I managed to implement that using Django,Jquery, AJAX and the searchForm below . What I want is when the user click search from index.html page, I process the form in the index view and redirect another page with additional parameters to another view. The problem is, once the user selected the fields and click 'search' nothing happens even though I redirected to another page in the form action and also in a view in model.py class Quiz(models.Model): slug= models.SlugField('subject-grade-year') grade= models.ForeignKey() subject= models.ForeignKey() year= models.ForeignKey() in form.py class SearchForm(forms.Form): grade = forms.ModelChoiceField( queryset =Grade.objects.all(),to_field_name="grade",required=False) subject = forms.ModelChoiceField(queryset=Subject.objects.none(), required=True ) year = forms.ModelChoiceField( queryset=Exam.objects.none(), required=True ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) index.html <form id="searchForm" action="{% url 'exam:taketest' %}" method="POST" data-url-types="{% url 'exam:subjects_choices' %}" … -
The scheduler seems to be running under uWSGI, but threads have been disabled
i am use the background task in my django project and if i run my project on pythonanywhere then it give me error The scheduler seems to be running under uWSGI, but threads have been disabled. You must run uWSGI with the --enable-threads option for the scheduler to work. please tell me how i solve it but i run my project in local host it work proparly i use django_scheduler for create a background process please tell me how can i solve my error this is my task.py from django.utils import timezone from clicknetapp.models import iptable from datetime import timedelta from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), "default") @register_job(scheduler, "interval", seconds=600) def delete_ip(): for record in iptable.objects.all(): exp = record.created_date + timedelta(minutes=10) if exp <= timezone.now(): record.delete() register_events(scheduler) -
How to keep the ML model of Spacy running in a Django app
I am working on an NLP project in SpaCy. I want to deploy my project on the internet using Django, but I have a performance issue. The app checks a sentence for its grammatical correctness and it is fast once the ML model is loaded with the command spacy.load('en'). The problem is that loading the ML model takes around 30 seconds. How can I keep the ML model running so that it doesn't have to reload/restart every time a new request comes in on the server? -
Django/Python sendmail with google including Bcc
Im trying to include Bcc emails to my sendmail script: I removed all exceptions for this moment... USERNAME = "my gmail login email" PASSWORD = "APP Pass" SMTPserver = 'smtp.gmail.com' sender = USERNAME to_recipient = 'to_recipient @gmail.com' bcc_email = 'bcc_email @gmail.com' msgHtml = "<b>Test message</b><br>with html" subject = "Sent from Python" import sys from smtplib import SMTP_SSL as SMTP from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart msg = MIMEMultipart('alternative') msg['Subject'] = subject msg.attach(MIMEText(msgHtml, 'html')) conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.login(USERNAME, PASSWORD) conn.sendmail(sender, to_recipient, bcc_email, msg.as_bytes()) But I get the error from smtplip 'int' object has no attribute 'lower' And when I try to change this one line conn.sendmail(sender, [to_recipient, bcc_email], msg.as_bytes()) Then all Emails are in Bcc, also thr To Email is in Bcc and To Email is empty How should that look right? I use that in Django, but it shouldn't really matter. -
Django exclude single value from query
Given a model, let sat MyModel, I want to extract from it all objects associated to a certain entry and exclude all of them that contain the 'foo' world a certain field (let's say custom_name). I've found the following solution: all_entries = MyModel.objects.filter(entry=foo_entry) for el in all_entries: if 'foo' in el.custom_name: all_entries.remove(el) break There is a better and more performing way to do it? -
Django Set Head Attributes with include
I'm creating a Django app. I want to include a HTML-File to set default meta tags (like description, ogDescription etc...). I already tried this Django set default value with include. Here are my files: set_head_attributes.html {% block description %}{{ model.description }}{% endblock %} {% block ogDescription %}{{ model.short_description }}...{% endblock %} {% block keywords %} {% for author in model.authors.all %} {{ author.get_full_name}}, {% endfor %} {{ model.category }}, {% for word in keywords %} {{ word} }, {% endfor %}, {% endblock %} {% block author %}{% for author in model.authors.all %}{{ author.get_full_name }}, {% endfor %}{% endblock %} {% block ogImage %} {% if model.topImage is not None %} {{ model.topImage.file.url }} {% elif model.image_set.all.first is not None %} {{ model.image_set.all.first }} {% endif %} {% endblock %} I'm including this with: {% include "filters/set_head_attributes.html" with model=article %} -
Handling Ajax request in Django without form
I have a list of things in my html with an ajax request to pass the data-measure value to views.py : <ul> <li><a class="measure" href="#" data-measure="m_0001">Measure_0001</a></li> <li><a class="measure" href="#" data-measure="m_0002">Measure_0002</a></li> <li><a class="measure" href="#" data-measure="m_0003">Measure_0003</a></li> </ul> Javascript $(".measure").click(function(){ var measure = {'measure': this.getAttribute("data-measure")}; $.ajax({ url : "prueba/", // the endpoint type : "POST", // http method data : measure, success : function (data) { //Success } }); In this file views.py I want to get the value to make a query to my database. def prueba(request): response_data = '{}' if request.user.is_authenticated: if request.method == 'POST': measure = request.POST.get('measure', None) //request to database return JsonResponse(response_data, safe=False) else: response_data = '{"nothing to see": "this is not happening"}' return JsonResponse(response_data, safe=False) When I click the item of the list, I have this error: "Forbidden (CSRF token missing or incorrect.)" I do not understand where I have to put the csrf_token in order for it to work. Any suggestions? -
UnicodeEncodeError raised when 'createsuperuser' is called
I am trying to deploy my Django application (2.1.5 with Python 3.6.6) on my server with a PostGreSQL database. I did a 'makemigrations' and 'migrate' as usual and then I can't create a super user with the command 'createsuperuser': [alex@web574 myproject]$ python3.6 manage.py createsuperuser Nom d'utilisateur (leave blank to use 'alex'): Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/alex/webapps/global_hse_project/lib/python3.6/Django-2.1.5-py3.6.egg/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/alex/webapps/global_hse_project/lib/python3.6/Django-2.1.5-py3.6.egg/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/alex/webapps/global_hse_project/lib/python3.6/Django-2.1.5-py3.6.egg/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/alex/webapps/global_hse_project/lib/python3.6/Django-2.1.5-py3.6.egg/django/contrib/auth/management/commands/createsuperuser.py", line 60, in execute return super().execute(*args, **options) File "/home/alex/webapps/global_hse_project/lib/python3.6/Django-2.1.5-py3.6.egg/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/alex/webapps/global_hse_project/lib/python3.6/Django-2.1.5-py3.6.egg/django/contrib/auth/management/commands/createsuperuser.py", line 139, in handle input_value = self.get_input_data(field, message) File "/home/alex/webapps/global_hse_project/lib/python3.6/Django-2.1.5-py3.6.egg/django/contrib/auth/management/commands/createsuperuser.py", line 194, in get_input_data raw_value = input(message) UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 8: ordinal not in range(128) I found on Google to add: # -*- Coding: utf-8 -*- at the top of the file but it doesn't work, same result with the variable DEFAULT_CHARSET (https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-DEFAULT_CHARSET). My PostGreSQL database are asking for utf-8 encoding. -
Django bulk_create IntegrityError (Duplicate entry) with UUID primary_key
I'm trying to save a huge amount of objects in a model, so I decided to use bulk_create by this way: while True: batch = list(islice(records, 100)) if not batch: break models.Record.objects.bulk_create(batch, batch_size) But I get this error when I add the second batch of 100: django.db.utils.IntegrityError: (1062, "Duplicate entry '165ab345f2ad47bbb2072ab7b3e8023f' for key 'PRIMARY'") This is the model if it helps you: class Record(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... Thanks in advance. -
Drf unique_together prevent destroy in viewset
I have a model with unique_together constrain class ExampleModel(models.Model): id = models.AutoField(primary_key=True) cmp = models.ForeignKey('Titles', on_delete=models.PROTECT) env = models.CharField(max_length=32) class Meta: unique_together = ( 'cmp ', 'env ', ) A serializer with the above fields: class ExampleModelSerializer(serializers.ModelSerializer): class Meta: model = ExampleModel fields = ('id', 'cmp ', 'env') And in viewsets the following destroy method: def destroy(self, request, pk): serializer = self.get_serializer(data=request.query_params) serializer.is_valid(raise_exception=True) instance = self.get_object() self.perform_destroy(instance) On the line serializer.is_valid() breaks with the following error: {"non_field_errors":["The fields cmp, envmust make a unique set."]} Any ideas why it happens and what is the proper solution to sovle it -
Delete View With Confirmation Prompt - Django
I want to delete compoany with Confirmation Prompt. I dont want to redirect to new template. class CompanyDeleteView(LoginRequiredMixin, generic.DeleteView): model = Company template_name = 'company/company_confirm_delete.html' -
Cannot import models to signals.py or tasks.py (django)
I'm having trouble importing models in my django apps. my app api is installed and migrated and visible in the admin I can add records through admin so the model is working. for some reason when I try to import the model to signals.py to I get an error I'm using django 2.0 signals.py is located in the same directory as the model. Has django changed the way you import models? I was under the impression that was the way. from api import testModel ModuleNotFoundError: No module named 'api signals.py from api.models import TestModel from django.dispatch import receiver from django.db.models.signals import pre_save, pre_delete, post_save, post_delete from django.dispatch import receiver from api.models import testModel @receiver(post_save, sender=testModel) def update(sender, instance, created, **kwargs): if instance.status == 'inplay': print('this is inplay') send() -
How can I use Django to have persistent session variables?
I have a trigger in my database that will automatically update the row_modified_by_user column based on the value of a session variable. To do this in Django, I believe I would have to put this in my settings.py file: 'my_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db_name', 'USER': 'my_db_user', 'PASSWORD': '******', 'HOST': 'my_host', 'PORT': '12345', 'OPTIONS': { 'init_command': "SET @SessionForUser = '" + CURRENT_USER + "'", } } Now, CURRENT_USER is the user being logged in. How do I pass this value from my views.py to my settings.py? Note that I can't use a connection cursor in my views.py because the connection is not persistent, it is closed afterwards so the session variable is cleared after it executes the command: with connections['my_db'].cursor() as cursor: cursor = connection.cursor() cursor.execute("SET @SessionForUser = '" + CURRENT_USER + "'") I can't use global variables either because this is used only for reading (not writing) values: settings.CURRENT_USER = username What would be a good alternative for this? Maybe I am approaching this problem incorrectly? -
(Noob Question) Why is checking if the user is the author of a blog post completely different in .py and .html files?
in views.py if self.request.user == post.author in .html {% if object.author == user %} Can someone provide an explanation or a place that explains why this is so different? My understand is that {% /// %} runs the python code within it. Why in the html does it refer to only 'object.author' instead of 'post.author? How is object specific enough? -
Insert list in sqlite table with django
I am new to Django and I need some help. I am trying to make sqlite3 database with Djnago. I have created class in models.py, which looks like this: class Data(models.Model): vendor_name = models.CharField(max_length=100) product_name = models.CharField(max_length=100) versions = models.TextField() description = models.TextField() date = models.DateTimeField(default=timezone.now) I am trying to insert list of data in field named versions. List looks like this: ['8.0.1', '8.0.2', '8.0.3', '8.1.2'] At the end I would like to check, if list contains specific value, for example I would like to check if list contains 8.1.2. If value is in list it should return True. I am able to insert data in database like this: data = Data(vendor_name='paloalto', product_name='PA', versions=['8.0.1', '8.0.2', '8.0.3', '8.1.2'], description='...') data.save() I do not know how to check if database contain specific value in versions field, I will appreciate any help. -
How can I use callback method in Overwrite storage class for django save method?
I want invoke a callback method once I try to call save mthod of my overwrite method, but is doesn't seem to work. below is my code. class OverwriteStorage(Storage): def save(self, name, content, max_length=None, callback=None): """ Save new content to the file specified by name. The content should be a proper File object or any Python file-like object, ready to be read from the beginning. This method is modified to take care of callbacks for S3 storage class of amazon. So that user specific callback can be accommodated. :param name: name of the file. :param content: content of the file :param max_length: max length of the file. :param callback: callback method. :return: """ # Get the proper name for the file, as it will actually be saved. if name is None: name = content.name if not hasattr(content, 'chunks'): content = File(content, name) name = self.get_available_name(name, max_length=max_length) return self._save(name, content, callback=callback) but when I am trying to call this: file.file_location.save(name_of_the_file, File(open(str(name_of_the_file), 'r')),callback=ProgressPercentageUpload(name_with_extension, device_build)) It throws below error: TypeError: save() got an unexpected keyword argument 'callback' Is there anything I am doing wrong? Thanks for the help. -
plpgsql variadic parameters and passing arrays from Django using Python
I am trying to call a stored proc on Postgres/PGPLSQL from Django/Python. I have the stored proc defined using a VARIADIC parameter: CREATE OR REPLACE FUNCTION udf_getmultiplecategoriescodetypes (VARIADIC NUMERIC[]) then the only place I want to use the array of parameters in the proc is in the WHERE stmt: WHERE cct.code_category_fk_id = ANY($1) All this works perfectly when I call the function from the DBeaver console: SELECT * FROM udf_getmultiplecategoriescodetypes(1, 2) However, if I use the callproc function in Django/Python, using the same type of syntax, like this: c.callproc("udf_getmultpilecategoriescodetypes", (1, 2)) I get errors: LINE 1: SELECT * FROM udf_getmultpilecategoriescodetypes(1,2) HINT: No function matches the given name and argument types. You might need to add explicit type casts. function udf_getmultpilecategoriescodetypes(integer, integer) does not exist Furthermore, in DBeaver, when the function is created and stored in the functions listing, if I try to delete it, it says the function cannot be found. Function Showing in TreeView Deletion Error Msg I've since found out that I can delete it by using DROP FUNCTION and including the VARIADIC parameter so it recognises it based on number and type of parameters. But why is it like that? So, two questions: What is the correct … -
How to use JavaScript within a Django template?
I have created a JS file in my project and created this method: function changeValue() { document.getElementById("change-paragraph").value = "Changed"; } In my template I have this: <button type="button" onclick="changeValue()">Click to change</button> <p id="change-paragraph">Not changed</p> When I click the button, nothing happens? This template extends my base.html file which includes this to use the JS method: <script src="{% static 'games/script.js' %}"></script> Why isn't this working? -
NoReverseMatch with 2 slug parameters in django
i have the following problem. I want to have a detailview on this url: 127.0.0.1:8000/category-name/product-name (category-name is a slugfield and product-name too) right from the index page. Please help :( My error: NoReverseMatch at /products/ Reverse for 'ProductDetail' with arguments '('new-things', 'flower-pot')' not found. 1 pattern(s) tried: ['products\\/\\<slug\\:category\\.slug\\>\\/\\<slug\\:product\\.slug\\>$'] my (relevant part) index.html: {% for p in Product %} <a href="{% url 'product:ProductDetail' p.category.slug p.slug %}">{{ p.name}}</a> {% endfor %} my (relevant part) urls.py: from .models import * app_name = 'product' urlpatterns = [ path('product/<slug:category.slug>/<slug:product.slug>', views.ProductDetailView.as_view(), name="ProductDetail"), ] and (relevant part) my models.py: class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() slug = models.SlugField(blank=True, null=True) def save(self, *args, **kwargs): if not self.id: # Newly created object, so set slug self.slug = slugify(self.name) super(Product, self).save(*args, **kwargs) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) description = models.TextField() slug = models.SlugField(blank=True, null=True) def save(self, *args, **kwargs): if not self.id: # Newly created object, so set slug self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) def __str__(self): return self.name -
Remove a specific user from a Django Channels group?
I have a couple of Django Channels groups that I use to send various messages to the client with. Can I remove a specific user from one of these groups, using only the ID of the user I want to remove? Another potential option would be to force disconnect the users connection using just their ID. -
Unable to to return a list instead of a queryset in my filter class
I am trying to return a list instead of a queryset in my filter class's queryset function and I am unable to do it. It is redirecting me to a url with ?e=1 when I try to use the filter link class InstructorAttendanceFilter(SimpleListFilter): # right admin sidebar sub heading just above the filter options. title = _('Attendance Date') # Parameter for the filter that will be used in the URL query. parameter_name = 'skipped_dates' def lookups(self, request, model_admin): return ( ('reverse', _('reverse')), ) def queryset(self, request, queryset): qs = InstructorAttendance.objects.filter(instructor=request.user).exclude(instructor=request.user) sch = Schedule.objects.filter(instructor=request.user) range_date = [] for s in sch: # Some nested logic if q.lecture_date != day: range_date.append(( ('id', '00'), ('instructor',request.user), ('course_name', s), ('lecture_date', day), ('loggedin_date', timezone.now) )) none_qs = InstructorAttendance.objects.none() qslist = chain(qs, range_date) if self.value() == 'reverse': return qslist else: return queryset Usage in InstructorAttendanceAdmin: list_filter = ('instructor', 'lecture_date', InstructorAttendanceFilter) -
Django Rest Framework TypeError with browsable API only
Consider the following viewset: class FooBarView(viewsets.ModelViewSet): serializer_class = FooBarSerializer permission_classes = [IsAuthenticated] def list(self, request, *args, **kwargs): instance = self.get_queryset() serializer = self.get_serializer(instance) return Response(serializer.data) def get_queryset(self): user = self.request.user return FooBar.objects.filter(user=user) the following model: class FooBar(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) other fields ... and the follwing serializer class FooBarSerializer(serializers.ModelSerializer): class Meta: model = FooBar fields = ('user', other fields ...) This viewset works perfectly with the JsonRenderer, but the BrowsableAPIRenderer raises a TypeError on both the retrieve and list routes: __str__ returned non-string (type NoneType) /home/ubuntu/venv/lib/python3.6/site-packages/rest_framework/relations.py in display_value, line 228 def display_value(self, instance): return six.text_type(instance) Local Vars instance: Error in formatting: TypeError: __str__ returned non-string (type NoneType) self: PrimaryKeyRelatedField(allow_null=True, queryset=User.objects.all(), required=False, validators=[<UniqueValidator(queryset=FooBar.objects.all())>]) If i remove the user field from the serializer it works fine. The FooBar instance has a user, all of the others fields are as intented as well. Any idea where this could come from ? I'm running python3.6 with django2.0 and DRF3.9.0 -
Daphne issue when upgrading django from 1.11 to 2.0
When upgraded from django 1.11 to 2.0 this happens: Traceback (most recent call last): File "/home/.local/share/virtualenvs/django2/lib/python3.6/site-packages/daphne/http_protocol.py", line 179, in process "server": self.server_addr, TypeError: object() takes no parameters Django version 2.0.10, channels=2.1.6, daphne=2.2.4. This happens as soon as a GET request is sent to localhost:8000. Tried with manage.py runserver 0.0.0.0:8000. Offending line: self.application_queue = self.server.create_application(self, { "type": "http", # TODO: Correctly say if it's 1.1 or 1.0 "http_version": self.clientproto.split(b"/")[-1].decode("ascii"), "method": self.method.decode("ascii"), "path": unquote(self.path.decode("ascii")), "root_path": self.root_path, "scheme": "https" if self.isSecure() else "http", "query_string": self.query_string, "headers": self.clean_headers, "client": self.client_addr, "server": self.server_addr, # <<<<<<<<< OFFENDING LINE }) -
Sending free text messages on the phone using gmail, Django, Pyhon
I noticed today an addon to google chrome that allows you to send free text messages from gmail. Does anyone know any simple Api to implement this to the django application? Any help will be appreciated. -
How to tell Django third-party sitemaps to render https locations?
I use protocol = 'https' in my sitemaps but I also include predefined sitemaps from third-party apps. And they generate http links. I know I can inherit them and override protocol property but is there any site-wide solution without redefining every sitemap?