Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
problems with Python Django NSException
I am working on a project using Django and Python and I am trying to plot a simple graph using matplotlib and I keep getting the error "uncaught exception of type NSException", python also crashed after that. I am using mac if that helps. I have already tried using the most simple graphs but still the problem persists. This is my code in the views.py file def get_svg(request): t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='Sample') ax.grid() response = HttpResponse(content_type = 'image/png') canvas = FigureCanvasAgg(fig) canvas.print_png(response) return response print("hello") This is the error message I get: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSWindow drag regions should only be invalidated on the Main Thread!' terminating with uncaught exception of type NSException -
When using my Custom Filter in Django Filters I do not have a 'Submit' button
As the title says I made my own custom filter class, and when I clock on 'Filters' on Django-Rest page I get the search bars, but not 'Submit' button: Example of what I mean Here's my views.py def get_views(): ret_views = {} # loops through all the models in the program and sets up the view for it for model in apps.get_models(): if model._meta.app_label in settings.API_BLACKLIST: continue # creates the view for the api for the specific model class GenericView(viewsets.ModelViewSet): # permission_classes = (permissions.IsAuthenticatedOrReadOnly,) # if you're not logged in you can only read parser_classes = (MultiPartParser, JSONParser, FormParser) serializer_class = create_serializer(model) queryset = model.objects.all() # IMPORTANT: ONLY WORKS WHEN MODELS ARE PROPERLY ROUTED filter_backends = (DjangoFilterBackend,) filter_class = create_filter(model) # changes the name of the class so it will be displayed in the api properly GenericView.__name__ = model.__name__ + "View" ret_views[model.__name__] = GenericView return ret_view Here's my filters.py # edit the standard filter so it does a more general search instead of an exact search class CustomFilterSet(FilterSet): @classmethod def get_fields(cls): fields = super().get_fields() for name, lookups in fields.items(): lookups[:] = ['icontains'] return fields # creates a custom filter with which ever model is passed into it def create_filter(desired_model): class … -
How to edit django-allauth templates?
I have already tried to move files to PROJECT_ROOT/TEMPLATES/ a project and write to apps.py template dirs -
How to format html content before save in Django/Wagtail?
I'm using Wagtail as a headless CMS, and I created a block to insert code, but by saving it it saved exactly the html tags I typed, and rendering this on the front end is rendered as html content. For example, if I enter: <h1>Hello<h1/> he'll save just that way. I need a representation of this, but without actually being a valid html, since this will be rendered as html on the front end, inside pre and code tags. I know there are some htmls that represent things like "<" and ">". But I do not know how to solve this. There are also things I need to convert when saving, such as a new line inserted in the code, it should be saved as "" And the spaces are also being saved as white space, and when rendering html, all spaces are "converted" to one, so I also need a representation for those spaces. -
Django M2M filed validation for defined types
I have got a situation where i have couple of type choices for model in Django. i am willing to validate while making curd operations on M2M field? here is an example of Django model: class Employee(models.Model): TYPE_CHOICES = ( (1, 'OWNER'), (2, 'STAFF') ) name = models.CharField(max_length=30, blank=True) type = models.SmallIntegerField(choices=TYPE_CHOICES, default=2) staffs = models.ManyToManyField('self', symmetrical=False) def __str__(self): return f'{self.id}: {self.name}: {self.type}' def clean(self): """How to validate if adding staff is of type `STAFF`?""" """would like to check type of child object here?""" pass How can i validate all staff objects when i am adding staffs for a owner object? staff = Employee.objects.create(name='emp1') owner = Employee.objects.create(name='emp1', type=1) owner.staff.add(staff) -
I'm geting a name error where it can't find my model
I'm making a view to show a list of patients entered by a user. so i used django-tables module to render the table. in tables.py class PatientTable(tables.Table): FirstName = tables.Column(linkify=("PatientDetailView", {"pk": tables.A("Patient.pk")})) LastName = tables.Column(linkify=("PatientDetailView", {"pk": tables.A("Patient.pk")})) Telephone_no = tables.Column(linkify=("PatientDetailView", {"pk": tables.A("Patient.pk")})) class Meta: model = Patient # attrs = {'class': 'table table-striped table-hover'} exclude = ("doctor", "Notes", "Address") template_name = 'django_tables2/bootstrap4.html' # this is the view def Patients_list(request): table = PatientTable(Patient.objects.filter(doctor=request.user)) return render(request, 'accounts/patients_list.html',{ 'table' : table }) but when i reach to my url it returns Name error and i can't really see why. Is there a better method for doing that and delivering a table view of the patients of the doctor only and it's well stylized ? 'name 'Patient' is not defined' -
Django - How do I properly send a list from template to AJAX to view?
I'm trying to make an AJAX get request to the server whenever a user clicks a button. My problem is that I'm trying to return a list of dictionaries to the view. JQuery sees the object as a string, so technically I guess it's already in a JSON format. When I send it to the view the view sees it as a Querydict and when I try to index it, it only returns singular characters of the string. When I try to call json.loads(cameras) in views.py, it throws an error saying: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2) I know this is probably an issue with how I'm handling the variable on the front end side, but I'm not sure how to fix this issue. Should I initially pass the variable from the view to the template differently? views.py def trigger_sirens(request): # Retrieve the list of dictionaries cameras = request.GET.get('cameras') print(type(cameras)) # ==> <class 'str'> print(cameras) # ==> [{'name': 'camera1', 'site': 'city'}, {'name': 'camera2', 'site': 'city'}] print(cameras[0]) # ==> [ # Manipulate data return JsonResponse({'success': True}, status = 200) # This is just a placeholder for now siren_search.html <!-- A button to trigger … -
django.core.exceptions.ValidationError value must be a decimal number
So, I have two different django models, I want to fill one field in one model (that is configured as CharField) with some string, based on a condition, what string is in an other model. I wrote a simple method for that: method screenshot In next method of a class I'm trying to call this method inside of a creating and saving a model instance:model creating and saving When I run this via django management command, I'm receiving this error:error screenshot Both fields (first I'm taking from another model in a method on a first screenshot, second I'm trying to save in a DB) configured as CharField:first field second field I had tried to reset migrations and to drop and create a DB (PostgreSQL 11.4), that hadn't helped. my 0001_initial.py migration And my \d+ tablename result from a psql table information I had found some similar question here, but nothing had helped, I had tried: reset migrations, cast a string as a Decimal built-in instance I don't have so much expirience in django and I could make a silly mistake, but I spent troubleshooting around 12 hours already, so I decided to write a question here. -
Django Tutorial app, part 2. Why is missing - add field Question to Choice after makemigrations command?
I'm following the tutorial 2.2 Writing your first Django app, part 2. I created the models Question and Choice in the polls/models.py file like the tutorial. from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) I activated the poll app in the mysite/settings.py file. INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Then i run the command makemigrations but in the output is missing "- Add field question to choice". $ python manage.py makemigrations polls Migrations for 'polls': polls/migrations/0001_initial.py - Create model Question - Create model Choice I'm using the following versions: /mysite$ pip freeze Django==2.2.2 pkg-resources==0.0.0 pytz==2019.1 sqlparse==0.3.0 /mysite$ python --version Python 3.7.3 I deleted all the project and start again without success. -
Django 1.8 Conditional expression returns empty queryset
I have two models that are something like this: class Foo(models.Model): # fields... class Bar(models.Model): foo = models.ForeignKey(Foo) is_done = models.BooleanField() # more fields.... I would like to annotate Foo with a count of all the associated Bar objects for which is_done is true. Unfortunately, I am trapped in Django 1.8, so Count('bar', filter='bar__is_done) is not an option for me. So instead, I used a conditional aggregation: Foo.objects.all().annotate( # other fields... done=Count(Case( When(bar__is_done=True, then=1), output_field=IntegerField() )) ) Unfortunately, this returns an empty queryset. Removing the conditional returns a queryset as normal, but the last annotation in particular seems to break the query. What's wrong? -
directory problem when starting apache for django (wsgi)
after having created a small local web application with django, I want to be able to access it remotely by hosting it with apache and nginx and gunicorn. However I have an error on the directory entered in /etc/apache2/apache2.conf I get the following error when starting apache: "Job for apache2.service failed because the control process exited with error code" Recording after in detail, I saw this error: "apache2: Syntax error on line 235 of /etc/apache2/apache2.conf : Expected </Directory\xc2\xa0/home/pi/Desktop/ecole> but saw </Directory>" My additions in the apache2 conf files: WSGIScriptAlias / /home/pi/Desktop/ecole/école/école/wsgi.py WSGIPythonPath /home/pi/Desktop/ school/ <Directory /home/pi/Desktop/school> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> I don't understand the problem, thank you for coming back. -
Searching in Foreign Key Fields in Django Haystack
I want to search from a Foreign Key field in Django. I am using ElasticSearch as a backend search engine. It's working perfect for local fields that is , non foreign key fields Many sites said to create a prepare_<> function , but even after that I couldn't figure out why its not working. Here is my code. search_indexes.py class UploadFileIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True, indexed=True) #OtherFields Types = indexes.CharField(model_attr="Types") def get_model(self): return UploadFileModel def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().Objects.all().select_related('Types') def prepare_Types(self, obj): #Even after doing this its not working return '' if not obj.Types else obj.Types.Name views.py class search(SearchView): form_class = UploadFileSearch template_name = 'search/search.html' queryset = SearchQuerySet().filter() form.py class UploadFileSearch(SearchForm): q = forms.CharField(required=False, label=('Search'), widget=forms.TextInput(attrs={'type': 'search'})) def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.q = data.get('q', []) super(UploadFileSearch, self).__init__(*args, **kwargs) def search(self): if not self.is_valid(): return self.no_query_found() if not self.cleaned_data.get('q'): return self.no_query_found() sqs = self.searchqueryset.filter(SQ(Type__exact=self.q)) if self.load_all: sqs = sqs.load_all() return sqs models.py class TypeModel(models.Model): Name = models.CharField(default="", max_length=5, null=False) Objects = models.Manager() def __str__(self): return self.Name class UploadFileModel(models.Model): #Other fields Types = models.ForeignKey(TypeModel, on_delete=models.CASCADE,related_name="Types") model_text.txt #other objects... {{ object.Types}} I expect the output for searching pdf to … -
How to secure post/put/patch payload with in Django views?
I've been using django serializers for a while now, And it seems like any time I send a payload using put/post/patch, serializers.is_valid() only checks if the payload data attributes types are correct, required ones are present and does not check if there are surplus data in the payload not defined in models.py Let's say that I have models.py : class Task(models.Model): title = models.CharField(max_length=100, default='default_task_name') description = models.CharField(max_length=1000, blank=True, default='') complete = models.BooleanField(default=False) canceled = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('id', 'date') In my serializers.py i have the following : from rest_framework import serializers from .models import Task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' In my views.pyI have the following : class TaskDetails(APIView): def get_object(self, pk): try: return Task.objects.get(pk=pk) except Task.DoesNotExist: raise Http404 def put(self, request, pk): data = JSONParser().parse(request) serializer = TaskSerializer(self.get_object(pk), data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) return Response(serializer.errors, status=HTTP_422_UNPROCESSABLE_ENTITY) using cURL : curl -X PUT -H "Content-Type: application/json" -d '{"title":"task_1", "description":"learning rest", "task_force":"undefined "}' "my_api_uri" I except 'errors': {'task_force': ['undefined attribute task_force', 'status_code': '422'} What is a work around here to make that check with the serializer ? -
Trying to create a general search using django filters for all the fields in a given model
So I am creating a custom filter for my model and I want all the fields in that filter not use 'exact' but 'contains', but I don't want to manually add all the fields. I am trying to do something like this: from django_filters import FilterSet from polls.models import Question, Choice from django_filters import rest_framework class ChoiceFilter(FilterSet): for field in Choice._meta.get_fields(): field = rest_framework.CharFilter(lookup_expr='icontains') #question = rest_framework.CharFilter(lookup_expr='icontains') #this works want to generalize this class Meta: model = Choice fields = '__all__' So the second line works, but my for loop doesn't and my filter uses 'exact' instead of 'contains' -
Getting a relay not permitted error with Exim4
I am currently getting the following error: 2019-06-28 14:45:41 no host name found for IP address 192.168.X.X 2019-06-28 14:45:41 H=(cabc5b9f0d80) [192.168.X.X] F=<noreply@X.X.X.X> rejected RCPT <example@exmple.com>: relay not permitted My update-exim4.conf.conf looks as follows: dc_eximconfig_configtype='smarthost' dc_other_hostnames='example.com; localhost.localdomain; localhost' dc_local_interfaces='127.0.0.1 ; ::1' dc_readhost='example.com' dc_relay_domains='*' dc_minimaldns='false' dc_relay_nets='smtpserver.url' dc_smarthost='example.com' CFILEMODE='644' dc_use_split_config='false' dc_hide_mailname='' dc_mailname_in_oh='true' dc_localdelivery='mail_spool' When I run echo "Subject: sendmail test" | sendmail -v example@exmple.com, I receive the email which leads me to believe the config is fine, HOWEVER, when I attempt to send the email via my django app that is hosted on the same server I get the above error. My app conf looks as follows: EMAIL_HOST = "example.com" EMAIL_PORT = 25 EMAIL_NAME = "exmaple" EMAIL_ALIAS = "noreply@X.X.X.X" EMAIL_HOST_USER = "" EMAIL_HOST_PASSWORD = "" EMAIL_USE_TLS = False EMAIL_BATCH_SIZE = 50 EMAIL_BATCH_PAUSE = 300 The error in the app's logs is as follows: Task scheduler.tasks.workflow_send_email[740b2e55-896e-4a75-9e19-4fa5562783e2] raised unexpected: SMTPRecipientsRefused({'example@example.com': (550, b'relay not permitted')},) ... smtplib.SMTPRecipientsRefused: {'example@example.com': (550, b'relay not permitted')} -
Django reverse 'str' object has no attribute 'get'
I am trying to use reverse method in django view but I got an exception 'str' object has no attribute 'get'. here is my view class AbandonTicketView(View): context = dict() template_name = "places/order_detail.html" def get(self, request, uidb64, token, ordercode): order = abandon_oder(uidb64, token, ordercode) if order is not None and order.paid is False: return reverse("order_detail", kwargs={"ordercode": order.code}) return redirect("tickets") view that I want to go: class OrderDetailView(LoginRequiredMixin, View): template_name = "places/order_detail.html" context = dict() def get(self, request, ordercode): order = Order.objects.get(code=ordercode) self.context["order"] = order self.context["key"] = settings.tycoon.STRIPE_PUBLISHABLE_KEY if order.send_count >= 3 and order.paid is False: self.context["abandon_ticket"] = "Order was canceled" return render(request, template_name=self.template_name, context=self.context) def post(self, request, ordercode): order = pay_for_ticket(ordercode, request.POST["stripeToken"], request.user) self.context["order"] = order return render(request, template_name=self.template_name, context=self.context) here is url: path("orders/<code:ordercode>/detail/", views.OrderDetailView.as_view(), name="order_detail"), path("tickets/", views.OrderedTicketsView.as_view(), name="tickets"), I don't really know why it happends, because I do the similar reverse earlier and everything works fine, but not now. Could you help me please to solve this problem? -
SPAM appears at the beginning of the message title
I have a problem with sending email messages. When I send a message from the contact form in django 1.5 and receive a message - the word SPAM appears at the beginning of the message title. Email address is not on blacklist. When I am sending message on my local machine, everything is OK. email = EmailMessage( 'Contact', message, 'mail@from.com', [form.cleaned_data['email'] ], ['bcc@addressbcc.com'], headers={'X-PremiumMailfilter-Spam-Flag': 'NO'}, ) email.send() -
How to include API views in app's urls when the API is just a bunch of views in a module?
I want to create some API views for my Django app. Given that I will not be using Django REST Framework nor creating a separate app for this API, how can I incorporate such views in my app? My idea is to create api.py module in the app's folder at the same level as views.py sit and write those views there. But how do I include such API's urls in the urls.py of the app, which currently looks like this?: from django.urls import path from . import views, # import api as well? app_name='analyzer' urlpatterns = [ path('', views.index, name='index'), #how to inlclude views from api.py here? ] -
?: (urls.W005) URL namespace 'main' isn't unique. You may not be able to reverse all URLs in this namespace
getting this error when i am using the python manage.py runserver this is my project url (mysite/url): from django.contrib import admin from django.urls import path, include from users import views as user_views urlpatterns = [ path('register/', user_views.register, name='register'), path('', include('main.urls')), path('admin/', admin.site.urls), path('about/', include('main.urls')), ] and this is my first app url (main/url) from django.urls import path from . import views app_name = 'main' urlpatterns = [ path('', views.blog, name='blog'), path("about/", views.about, name="about"), ] and this is my second app url(users/urls): actually there is no urls in my second app but the register template we will find it in second app. I will be thankful. if You find a solution :) -
SSL certificate thowing error on Mobile Network
My domain is: www.habibindustry.com I have set a Django host on Ubuntu 18.04 with Nginx, Gunicorn. Then I set up my certbot to install Let’s encrypt SSL. It is working fine with both Desktop and Mobile over wifi network. But when I switch to Mobile Network it says : The page you are trying to view can not be shown because the authenticity of the received data could not be verified. Here is SSL Lab report : https://www.ssllabs.com/ssltest/analyze.html?d=www.habibindustry.com These are the instructions from DigitalOcean I followed : https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 -
Detect in django view whether web sockets are connected or not
I am working on a project where websockets are being used extensively.Sometimes it happens that though message has been sent from django view but the client doesn't receive that message.On analyzing the logs i saw that sometimes messages are being sent even if websockets in the Group are connected or not. Like i have a django view in which if certain conditions are met then a message is sent to the Group.Its like this:- def send_message(request): #some existing lines of code if(some_condition): Group("receivers").send({"text":json.dumps({"key1":"value1","key2":"value2"})}) I want to know before sending the message to "receivers" Group whether websockets of this group are connected or not. If they are not connected then code should wait till the websockets get connected and then message is sent. So overall it should be like this: def send_message(request): #some existing lines of code if(some_condition): if(websockets_are_not_connected): wait_for_websockets_to_get_connected elif(websockets_are_connected): Group("receivers").send({"text":json.dumps({"key1":"value1","key2":"value2"})}) PS: I am using django=1.11,channels==1.1.8 and redis as a message broker. -
django.db.utils 2006, 'Can\'t connect to local MySQL \'/var/run/mysqld/mysqld.sock\'
Trying to docker-compose up and permanently bumping into the issue with SQL socket. here is my docker-compose.yml version: '3' services: web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" container_name: jl_backend volumes: - .:/jl_backend ports: - "8000:8000" depends_on: - db db: image: mysql:latest command: mysqld --default-authentication-plugin=mysql_native_password volumes: - "./mysql:/var/lib/mysql" ports: - "3307:3307" # changed the port from 3306 so that it doesnt bump into SQL restart: always environment: here is the error: jl_backend | return Connection(*args, **kwargs) jl_backend | File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 208, in init jl_backend | super(Connection, self).init(*args, **kwargs2) jl_backend | django.db.utils.OperationalError: (2006, 'Can\'t connect to local MySQL server through socket \'/var/run/mysqld/mysqld.sock\' (2 "No such file or directory")') jl_backend exited with code 1 -
How to synchronize my local PostgreSQL with my heroku database for my website built using Django?
I have created a website using Django as backend and recently hosted it with heroku. Also, I have uploaded my local database on heroku, now I have added some more rows in my local database and want to synchronize my local database with my heroku database so that whenever I add some items in my local database, it is also added to the heroku database. How should I proceed? -
Managing client connections with Django channels
Disclaimer: This is a bit of a systems design question. I googled where to post system design questions and found a meta stack exchange thread that suggested stack overflow was the place. Feel free to redirect me if that’s not true. I’m trying to accomplish real time speech to text with django + websockets. I’m using nexmo to make a call + stream the audio back to my server. I'm then streaming the audio to watson speech to text to get the transcripts. I'm then streaming the transcripts back to a react frontend via websockets. I've managed to do this with tornado, but would like to use django channels. I’m stumbling on how to create / persist a client websocket connection to watson within a consumer. Here’s a simplified version of my problem: In the receive method of a django consumer: I’m catching a specific message to open a client websocket connection to watson I’m streaming audio from nexmo -> my server -> watson def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] if message == “open”: self.watson = openWatsonWebsocket() if message == “audio”: sendAudioToWatson(self.watson) I’ve been having a hard time opening / persisting the watson websocket call. There is … -
How to perform incremental operator in django template
I'm trying to fetch the number unread messages in a chat, It works fine in the django shell but i ran into a problem in the template because i cant use incremental operator In the django shell, i used the following codes # After importing the required models unread = 0 for message in chat.messages.all(): if message.read != True: unread += 1 This works fine In the template, I used the code below {%for message in chat.messages.all %} {% with unread=0 %} {% if message.read != True %} {{unread+=1}} {% endif %} {% endwith %} <span class="badge badge-light badge" style="margin-top: 27px; font-size: 2.5em; float:right; border-radius: 1.0rem;">{{unread}}</span> {%endfor%} I want to be able to output the number of unread messages like i could in the django shell