Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django checking if an individual field has an error and not run clean()?
Is there a way to check if an inidividual field has not passed validation in django's clean() method for a form. I don't want to have to manually be checking if a required field is there: def clean(): cleaned_data = super().clean() half_day = cleaned_data.get('half_day') start_date = cleaned_data.get('start_date') end_date = cleaned_data.get('end_date') leave_type = cleaned_data.get('leave_type') extra_info = cleaned_data.get('extra_info') if start_date and end_date: if half_day: if start_date != end_date: self.add_error( 'half_day', 'Start and end date must be the same' ) -
Django Application running on AWS ECS Cluster and behind the Squid Proxy
I have a Django Python app running on AWS ECS Cluster and it's running behind the Squid Proxy. The application need to access AWS SSM to get the parameter and it always fails I think because of the proxy. The application cannot use the proxy setting that I have set in the UserData #cloud-boothook # Configure Yum, the Docker daemon, and the ECS agent to use an HTTP proxy # Specify proxy host, port number, and ECS cluster name to use PROXY_HOST=10.0.0.131 PROXY_PORT=3128 CLUSTER_NAME=proxy-test # Set Yum HTTP proxy if [ ! -f /var/lib/cloud/instance/sem/config_yum_http_proxy ]; then echo "proxy=http://$PROXY_HOST:$PROXY_PORT" >> /etc/yum.conf echo "$$: $(date +%s.%N | cut -b1-13)" > /var/lib/cloud/instance/sem/config_yum_http_proxy fi # Set Docker HTTP proxy if [ ! -f /var/lib/cloud/instance/sem/config_docker_http_proxy ]; then echo "export HTTP_PROXY=http://$PROXY_HOST:$PROXY_PORT/" >> /etc/sysconfig/docker echo "export NO_PROXY=169.254.169.254" >> /etc/sysconfig/docker echo "$$: $(date +%s.%N | cut -b1-13)" > /var/lib/cloud/instance/sem/config_docker_http_proxy fi # Set ECS agent HTTP proxy if [ ! -f /var/lib/cloud/instance/sem/config_ecs-agent_http_proxy ]; then echo "ECS_CLUSTER=$CLUSTER_NAME" >> /etc/ecs/ecs.config echo "HTTP_PROXY=$PROXY_HOST:$PROXY_PORT" >> /etc/ecs/ecs.config echo "NO_PROXY=169.254.169.254,169.254.170.2,/var/run/docker.sock" >> /etc/ecs/ecs.config echo "$$: $(date +%s.%N | cut -b1-13)" > /var/lib/cloud/instance/sem/config_ecs-agent_http_proxy fi # Set ecs-init HTTP proxy if [ ! -f /var/lib/cloud/instance/sem/config_ecs-init_http_proxy ]; then echo "env HTTP_PROXY=$PROXY_HOST:$PROXY_PORT" >> /etc/init/ecs.override echo "env NO_PROXY=169.254.169.254,169.254.170.2,/var/run/docker.sock" >> /etc/init/ecs.override echo … -
Django: How to drop default sqlite database?
I need to drop my database since I want to use a customized user model in my project. I've used the default database that is used when following the django introduction tutorial. I connect to the database through the terminal with python manage.py dbshell. Then, I locate the database: sqlite> .databases main: /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/mydatabase And I proceed to delete the database: $ rm /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/mydatabase $ rm /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/mydatabase rm: /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/mydatabase: No such file or directory But the database still shows up in the database connection: sqlite> .databases main: /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/mydatabase And when I try to detach, I get an error: sqlite> detach database main; Error: cannot detach database main Is this a problem? -
Django: limit_choices_to to current objects id
Im using Django 1.11.6 and trying to limit the choices of projectLeader in my Project class to a list of AbstracUser which have the Projects id in their ManytoMany field workingproject. class Project in models.py of one app class Project (models.Model): projectLeader = models.ForeignKey('anmeldung.AbstractUser', blank=True, null=True, limit_choices_to={'workingproject': limit},) class AbstractUser in models.py of application named "anmeldung" class AbstractUser(AbstractBaseUser, PermissionsMixin): workingproject = models.ManyToManyField('szenario.Project', blank=True) For 'limit' i've used several things like self.id, obj.id but cant figure out whats correct. I'm quite new to Django and all the similar questions i've found didnt help me (could be i just didnt get the answers). -
How to serialize a django QuerySet and a django object in one call?
I am trying to retrieve my object and a query set from my model through an ajax call. What I want to get back is an object and a query set. So when i serialize the object its no problem but the QuerySet does not seem to be serialized by Django. I get an error "QuerySet has no attribute _meta". Here is my code: def followUp(request): fid = request.GET['fid'] fup = FollowUp.objects.get(answer=fid) Question = fup.question answers = Question.answer_set.all() context = { 'question': Question, 'answers' : answers } data = serializers.serialize('json', context) return JsonResponse(data, safe=False, content_type="application/json") Here if i just put 'Question' its no problem but as soon as i try to make a dict with 'answers' combined, it throws the error. Is there a way to serialize both of them or what should I do if not? Please Help! -
How to filtering tag using Django2.0 and django-taggit0.22.1
I have a problem which i can't resolve. I try to implements tags features in my blog project in Python/Django 2.0. I install django-taggit0.22.1. Ok i have a class Post with atributte tags = TaggableManager() I also have a few posts object with tags. For example in python manage.py shell I import my Post models and I do command: post = Post.objects.get(id=1) i have a post named "Post: Django 2.0" then i use tag = post.tags.all() "tag" variable show me this "QuerySet [<\Tag: django\>], <\Tag: programming\>, <\Tag: jazz\>" ok and then i want to filter my tags. I download all my published post published= Post.published.all() and finally i want do filter post by tags using this: published.filter(tags__name__in=['music']) I see this error: TypeError: get_path_info() takes 1 positional argument but 2 were given What is the main problem ? This filtering method i saw on https://pypi.python.org/pypi/django-taggit Can you help me? -
Multiple Inheritance Django mixins
I have an issue with getting Django view to work with two mixins that both override dispatch method. My view has the following signature: class SomeView(LoggingMixin, ResetUserLanguageMixin, generics.ListAPIView) The ResetUserLanguageMixin supposed to set the language in dispatch, but then set it back to what it was before the call in finally block. class ResetUserLanguageMixin(object): def dispatch(self, request, *args, **kwargs): cur_language = translation.get_language() try: response = super(ResetUserLanguageMixin, self).dispatch(request, *args, **kwargs) finally: translation.activate(cur_language) return response The issue is that generics.ListAPIView also has an implementation of dispatch that doesn't call super. The ResetUserLanguageMixin calls dispatch, where it sets the language, but also the finally block is called before the generics.ListAPIView dispatch is called. As a result incorrect language is used by generics.ListAPIView. The ideal situation would be that generics.ListAPIView dispatch is called from ResetUserLanguageMixin's dispatch before the finally block. Is this possible, and if so, how could it be accomplished? -
How to create schema from tree structure, create a api in django and generate a tree on browser?
Please generate schema using below image and generate api. Give me a perfect answer. -
Django 1.11 password reset not working
I've been researching about some other questions here about django password reset email not working and I tried it but I can't find a real solution. The problem is that I can send email through Django 1.11 without problem but it fails in password reset. It is just not sent. These are my url patterns: url(r'^password/reset/$', password_reset, {'template_name': 'registration/password_reset_form.html', 'email_template_name': 'registration/password_reset_email.html', 'post_reset_redirect': 'password-reset-done'}, name='password-reset'), url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'), url(r'^password/reset/complete/$', password_reset_complete, {'template_name': 'registration/password_reset_complete.html'}, name='password_reset_complete'), url(r'^password/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', password_reset_confirm, {'template_name': 'registration/password_reset_confirm.html'}, name='password_reset_confirm'), And my email settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ['EMAIL_USER'] EMAIL_HOST_PASSWORD = os.environ['EMAIL_PASSWORD'] SERVER_EMAIL = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = 'Team <noreply@whatever.com>' The templates exist and are working fine. I used the console email backend to test the email but it doesn't send anything and any error is shown at the console. Other views can send email without problem. -
foreign key appearing as char field
My foreign key that is event_id is being displayed as another attribute in my Expense class as Hall_name which is an attribute of Event class a char field. i don't know why because i have just did this. class Event(model.Model): event_hall=models.CharField(max_length=1) here are all my attributes but i let django make its own default primary key and it should be an integer. class Expense(models.Model) event_id=models.ForeignKey(Event) so why is it displaying it as event_hall in my foreign key? -
Django.fcgi using dynamic virtualenv
Is there a way to load the virtualenv in a dynamic way? #!/home/root/.virtualenvs/production/bin/python import os, sys ... I'd like the path to be #!/home/root/.virtualenvs/production/bin/python or #!/home/root/.virtualenvs/staging/bin/python depending if the folder name is staging or production I can get the folder name this way: _PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, _PROJECT_DIR) sys.path.insert(0, os.path.dirname(_PROJECT_DIR)) _FOLDER_NAME = _PROJECT_DIR.split('/')[-1] But I have no idea if I can load the virtualenv in a dynamic way based on this. It's a deployment issue, I currently have to replace the path in staging environment because it's hardcoded for production. -
Different error importing file-wide and function-wide Django
I am trying to run some tests in my Django project, but I get two different errors with two different appoaches. If I do from cards_browser.models import Cards, Drawers, Timeframes at the top of the file among the other imports, I get: RuntimeError: Model class cards_browser.models.Cards doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. However, the app is in fact in INSTALLED_APPS, among others: 'vcc_merged.cards_browser', But if I import specific models for the specific model I'm testing like so def test_data_count(self): from cards_browser.models import Cards I get: django.db.utils.ProgrammingError: (1146, "Table 'test_vcc.feedback' doesn't exist") Now the second is a problem with Django if you have unmanaged models like I do, but I have a TestRunner file in Settings that is supposed to make the models Managed for the duration of the test, but that obviously fails to work, or I wouldn't be getting this error. Using Python 3.6.3 and Django 1.11.7 connected to MySQL 5.7 -
Django many to many relationship
I have a user model and a group model. from django.contrib.auth.models import AbstractUser class Group(models.Model): name = models.CharField(max_length=200) class User(AbstractUser): name = models.CharField(max_length=200) group = models.ManyToManyField('Group') I have a scenario in which a user can be an admin or just a member of a group. A group can have many admins as well as it can have many members. How can I define such a relation in Django and query things like "Admins of a group", "members of group", "groups where a user is an admin", "groups where a user is a member" -
RabbitMQ is getting flooded by connection and disconnection
I have a very weird issue where my rabbimq gets a flooded log like the one below continuously as in milliseconds =WARNING REPORT==== 12-Dec-2017::11:52:44 === closing AMQP connection <0.27756.1813> (10.0.1.44:57706 -> 10.0.1.33:5672, vhost: 'peter1_vhost', user: 'peter1'): client unexpectedly closed TCP connection =INFO REPORT==== 12-Dec-2017::11:52:44 === connection <0.27588.1813> (10.0.1.44:57710 -> 10.0.1.33:5672): user 'peter1' authenticated and granted access to vhost 'peter1_vhost' =WARNING REPORT==== 12-Dec-2017::11:52:44 === closing AMQP connection <0.27562.1813> (10.0.1.44:57708 -> 10.0.1.33:5672, vhost: 'peter1_vhost', user: 'peter1'): client unexpectedly closed TCP connection =INFO REPORT==== 12-Dec-2017::11:52:44 === accepting AMQP connection <0.28103.1813> (10.0.1.44:57714 -> 10.0.1.33:5672) =WARNING REPORT==== 12-Dec-2017::11:52:44 === closing AMQP connection <0.27588.1813> (10.0.1.44:57710 -> 10.0.1.33:5672, vhost: 'peter1_vhost', user: 'peter1'): client unexpectedly closed TCP connection =INFO REPORT==== 12-Dec-2017::11:52:44 === connection <0.28103.1813> (10.0.1.44:57714 -> 10.0.1.33:5672): user 'peter1' authenticated and granted access to vhost 'peter1_vhost' =INFO REPORT==== 12-Dec-2017::11:52:44 === accepting AMQP connection <0.28178.1813> (10.0.1.44:57716 -> 10.0.1.33:5672) =INFO REPORT==== 12-Dec-2017::11:52:44 === connection <0.28178.1813> (10.0.1.44:57716 -> 10.0.1.33:5672): user 'peter1' authenticated and granted access to vhost 'peter1_vhost' =INFO REPORT==== 12-Dec-2017::11:52:44 === accepting AMQP connection <0.27644.1813> (10.0.1.44:57718 -> 10.0.1.33:5672) =WARNING REPORT==== 12-Dec-2017::11:52:44 === closing AMQP connection <0.28178.1813> (10.0.1.44:57716 -> 10.0.1.33:5672, vhost: 'peter1_vhost', user: 'peter1'): client unexpectedly closed TCP connection =INFO REPORT==== 12-Dec-2017::11:52:44 === connection <0.27644.1813> (10.0.1.44:57718 -> 10.0.1.33:5672): user 'peter1' authenticated … -
Djnago error no reverse match [duplicate]
This question already has an answer here: NoReverseMatch at /posts/post/18/comment/ Django Error 1 answer I've been getting this error, and I couldn't seem to fix it. Here is a screenshot of it: error image Here my view's.py: from django.shortcuts import render, get_object_or_404, redirect from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from posts.forms import PostForm, CommentForm from django.core.urlresolvers import reverse_lazy from django.http import Http404 from django.views import generic from braces.views import SelectRelatedMixin from . import forms from . import models from django.contrib.auth import get_user_model User = get_user_model() class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ("user", "group") class UserPosts(generic.ListView): model = models.Post template_name = "posts/user_post_list.html" def get_queryset(self): try: self.post_user = User.objects.prefetch_related("posts").get( username__iexact=self.kwargs.get("username") ) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["post_user"] = self.post_user return context class PostDetail(SelectRelatedMixin, generic.DetailView): model = models.Post select_related = ("user", "group") def get_queryset(self): queryset = super().get_queryset() return queryset.filter( user__username__iexact=self.kwargs.get("username") ) class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): # form_class = forms.PostForm fields = ('message','group') model = models.Post # def get_form_kwargs(self): # kwargs = super().get_form_kwargs() # kwargs.update({"user": self.request.user}) # return kwargs def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView): model = models.Post select_related = ("user", "group") … -
How to set a variable from one class equals to a variable in another class in Django models.py?
I am a new in Django world and I want to link two classes from models.py so that i can set their variables equal to each other. Here is the models.py code: from django.db import models from django.core.urlresolvers import reverse # Create your models here. class file(models.Model): title = models.CharField(max_length=250) FILE_TYPE_CHOICES = ( ('audio','Audio'), ('games','Games'), ('videos','Videos'), ('applications','Applications'), ('books','Books/Docs'), ('others','Others') ) file_type = models.CharField(max_length=10,choices=FILE_TYPE_CHOICES,default='others') description = models.TextField(max_length=6000) #uploader_username = ??? def get_absolute_url(self): return reverse('one:user') def __str__(self): return self.title class user (models.Model): username= models.CharField(max_length=100) email=models.EmailField password= models.CharField(max_length = 100) user_files = models.ForeignKey(file, on_delete=models.CASCADE) Here I want to set uploader_username from file class equals tousername from user class. -
Django Rest Framework + Python
Hello everyone, I'm beginner in python and Django rest And I stuck when I fetch data. **Here is my API** :- http://127.0.0.1:8000/subjects/course/23/ I want a all subject data according to course which I select..When I hit this api if single data present working awesome but when inside course_id multiple subject present then gives me error such as : Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one Subject -- it returned 2! Thanks in advance -
Is django-imagekit ready for Django 2.0?
Could you tell me whether django-imagekit is ready for Django 2.0? They doesn't seem to have announced that. But they mention "Test against Django 2.0" for their tox.ini. -
Which framework is best for Web Development using Python - Python Flask or Python Django?
Which framework is best for Web Development using Python - Python Flask or Python Django ? And which ever it is, Could you please provide me the best tutorial url. -
run django web application with apache and mod_wsgi with python3 virtuaenvironment on ubuntu
This is the first time I am deploying django app on apache with mod_wsgi,using python3 virtual environment. directory like below (DJango_RestFramework) User@User-virtual-machine:~/Project/Sample$ dir db.sqlite3 manage.py Sample static Added STATIC_ROOT = os.path.join(BASE_DIR, "/home/User/Project/Sample/static/") at the bottom of settings.py file then applied ./manage.py collectstatic right after then changed /etc/apache2/sites-available/000-default.conf file like below <VirtualHost :*80> Alias /static /home/User/Project/Sample/static <Directory /home/User/Project/Sample/static> Require all granted </Directory> <Directory /home/User/Project/Sample/Sample> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess Sample python-path=/home/User/Project/:/home/User/Project/DJango_RestFramework/lib/python3.5/site-packages WSGIProcessGroup Sample WSGIScriptAlias / /home/User/Project/Sample/Sample/wsgi.py </VirtualHost> finally applied these commands 1.chmod 664 /home/User/Project/Sample/db.sqlite3, 2.sudo chown :www-data /home/User/Project/Sample/db.sqlite3, 3.sudo chown :www-data /home/User/Project/Sample, 4.sudo service apache2 restart got Internal Server Error If I checked at error.log it' was showing that [Tue Dec 12 15:02:32.095065 2017] [wsgi:error] [pid 1331:tid 140188564576000] [remote 127.0.0.1:5937] ImportError: No module named 'django'. don't know where I mistaken please help me. thanks in advance! -
ppt open in Djanago
Django the powerpoint generated using python-pptx library has error message I am using this way But I am getting an Error " name 'Presentation' is not defined" what should I do? -
Bypass Django to serve static files with Nginx
I'm trying to serve static files with Nginx, but it seems like Django takes control of the path and keeps giving a 404 because it's not a valid URL within the Django app. Here's the Nginx server setup: server { listen 443; server_name localhost; client_max_body_size 500M; location /static/ { autoindex on; root /app/interfaces/web/static; } location / { uwsgi_pass django; include /app/interfaces/web/django/uwsgi_params; } } I have tried all following combinations: /static/ and /static With and without autoindex on root and alias When I try to access a file in the /static/ directory, I get the following 404 error from Django: Page not found (404) Request Method: GET Request URL: https://172.16.6.158/static/test.css Using the URLconf defined in django.urls, Django tried these URL patterns, in this order: ^ ^$ [name='index'] ^history/ ^config/ ^admin/ The current path, static/test.css, didn't match any of these. I also tried to set STATIC_URL in Django settings, but I don't think that should be neccessary since I'm trying to bypass Django. And I didn't make any difference anyway. Does anyone know what I'm doing wrong? Do I need to change configuration somewhere else. -
Is this an okay way of doing a Django Rest Framework Serializer Update Method?
I notice the DRF docs say you should pop each field off the validated_data dict in the update method as such: def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.created = validated_data.get('created', instance.created) instance.save() return instance However lets say you had a models with lots of fields. Would it not be easier to do something like the below? Or am I missing something? def update(self, instance, validated_data): for attr, value in instance.__dict__.iteritems(): new_value = validated_data.get(attr, value) setattr(instance, attr, new_value) instance.save() return instance Still learning Python so I'm not sure if I'm doing something unsafe or stupid here. -- Dean -
InterfaceError: connection already closed
I'm running a celery(4.1.0) task with django(1.11.6) using psycopg2(2.7.3), getting these errors after 5-6 hour of deploying the app on production.one of the related issue on django issue tickets. Tried various solution of reconnecting the connection using try and except, handling InterfaceError. Any help will be appreciated. Checked and Applied some of the solutions, but nothing seems to be working, Celery Worker Database Connection Pooling Traceback InterfaceError: connection already closed File "billiard/pool.py", line 358, in workloop result = (True, prepare_result(fun(*args, **kwargs))) File "celery/app/trace.py", line 537, in _fast_trace_task uuid, args, kwargs, request, File "celery/app/trace.py", line 482, in trace_task I, _, _, _ = on_error(task_request, exc, uuid) File "celery/app/trace.py", line 330, in on_error task, request, eager=eager, call_errbacks=call_errbacks, File "celery/app/trace.py", line 164, in handle_error_state call_errbacks=call_errbacks) File "celery/app/trace.py", line 212, in handle_failure task.on_failure(exc, req.id, req.args, req.kwargs, einfo) File "telemetry/tasks.py", line 29, in on_failure save_failed_task(self, exc, task_id, args, kwargs, einfo) File "telemetry/celery_failure.py", line 46, in save_failed_task existing_task_first = existing_task.first() File "django/db/models/query.py", line 564, in first objects = list((self if self.ordered else self.order_by('pk'))[:1]) File "django/db/models/query.py", line 250, in __iter__ self._fetch_all() File "django/db/models/query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "django/db/models/sql/compiler.py", line 882, in execute_sql cursor = … -
Which Web Framework should I Learn first Django or Node.js as a begginer? [on hold]
I have 6 months of front-end experience now i want to learn back-end web development so please help me which web framework should I choose Django or Node.js?