Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add seperate self contained php landing page to Django CMS
Completely new to Django and can't seem to find advice regarding this in the docs: In summary, there is a site that is built and managed with Django. I have a self-contained php landing page (with a form) ready to go, that I would like to integrate into the site and the URL structure like follows: djangosite.com/selfcontainedlandingpage I have access to the server to upload the site files but am very unfamiliar with the structure. (of course, I don't want or need this to be integrated into the CMS - just to be on the server and in the URL structure as above) Is this possible? Any advice or a point in the right direction greatly appreciated. -
dango-crispy-forms error keeps interferring with project even after uninstallation
I was trying to embed django crispy forms into my project which gave me an "Module not found" error which I couldn't figure. So, I uninstalled it, but even after uninstallation, this thing throws me this error when I run the local server and even migrate. (newvenv) root@localhost:~/my_website/python-getting-started# python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f286ba630d0> Traceback (most recent call last): File "/root/my_website/newvenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/root/my_website/newvenv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/root/my_website/newvenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/root/my_website/newvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/root/my_website/newvenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/root/my_website/newvenv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/root/my_website/newvenv/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/root/my_website/newvenv/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crispy_formshello' Can't help this problem...... -
How to log a user out in django (without the request)
In django I can log a user out with: from django.contrib.auth import logout logout(request) However, how would I manually log a use out -- for example I want to "sign users out of all tabs" -- that is, how do I flush all session for that user in my db? -
Django test database requires Postgres Extension enabled
I have a Django app which requires Postgres' fuzzystrmatch extension to be enabled on the database. Django's unittest framework creates and destroys a new database. I need this new database to have the extension turned on for testing. I can use './manage.py test --keepdb' to keep the database and then manually turn on the extension, but this is an ineloquent solution. Any idea how I can enable this extension programmatically? -
How to delete all nested objects referenced to an object?
I have a model which is set as foreign key in several models. Right now deleting any object from the model throws ProtectedError if it is referenced in any of those model. I want to let user delete the object with all protected objects in a single operation. I can delete the first layer of protected objects by simply calling .... except ProtectedError as e e.protected_objects.delete() .... But when the protected_objects have their own protected objects, the operation fails and throws another second layer ProtectedError. What I want to achieve is, deleting all the protected objects undiscriminating in which layer it exists. I am aware that it can be a dangerous operation to perform. But can I achieve this without a complex solution. Thanks in advance. -
AttributeError, 'AnimalType' has no attribute 'animals_set'
I get an AttributeError for some reason. "'Animal Type' has no attribute 'animals_set'" Here is the model its referring to: class AnimalType(models.Model): """Type of animal that can classify the animal""" owner = models.ForeignKey(User, on_delete=models.CASCADE) a_type = models.CharField(max_length=50, default='') date_added = models.DateField(auto_now_add=True) def __str__(self): return self.a_type Here is the function its being executed in: @login_required def animal_type(request, animal_type_id): """Shows a single animal type and all of the animals associated""" animal_type = AnimalType.objects.get(id=animal_type_id) #animal type belongs to user if animal_type.owner != request.user: raise Http404 animals = animal_type.animals_set.order_by('-date_added') context = {'animal_type':animal_type, 'animals':animals} return render(request, 'zoo_animal_feeders/animal_type.html', context) -
Issue while running Django and Nginx on separate docker containers
I am experimenting with docker containers. Trying to run a Django application in a Docker container and serving it using Nginx(not containerized) and it works fine. But when I am trying to containerize Nginx and use that container to serve the Django container it is not working. When I hit the IP of the server, I am able to get only the Nginx test page. So I am confused how to do it. I am using a similar Nginx.conf file in the container which is working initially. -
Docker does not copy all my static files?
I'm trying to run a django project in the docker container. The django project is running, but I can't see the styles because some of my static files aren't copied. Dockerfile: FROM python:3.6 RUN mkdir -p /opt/services/djangoapp/src WORKDIR /opt/services/djangoapp/src COPY Pipfile Pipfile.lock /opt/services/djangoapp/src/ RUN pip install pipenv && pipenv install --system COPY . /opt/services/djangoapp/src EXPOSE 8000 CMD ["gunicorn", "--chdir", "udk", "--bind", ":8000", "mydjango.wsgi:application"] When I write COPY . /opt/services/djangoapp/src as above , I can only see the following static folders in the target directory: βββ static βββ admin βββ ckeditor therefore, my still files are not uploaded and I am only viewing text on the site. my project tree: βββ config β βββ nginx β β βββ mydjango.conf β βββ requirements.pip βββ docker-compose.yml βββ Dockerfile βββ src βββ manage.py βββ mydjango βββ __init__.py βββ settings.py βββ urls.py βββ wsgi.py βββ static βββ admin βββ ckeditor βββ css βββ js βββ img I want to copy all the files in the static folder inside the container. How can I do this? I'm missing something. -
Django Haystack override class's index_queryset in subclass
I'm using Django Haystack (with Aldryn Search) to search content on a client site. However, we need to modify the Articles indexed from the Aldryn NewsBlog plugin - Articles assigned to the Intranet Section should not be indexed. So I made a subclass in my plugin to override that like the documentation says to do: Subclasses can override this method to avoid indexing certain objects. However, when I try to rebuild the index it says: aldryn_newsblog.models.Article has more than one 'SearchIndex`` handling it. Please exclude either aldryn_newsblog.search_indexes.ArticleIndex object or search_modifier.search_indexes.BlogHelperIndex object The documentation is not clear to me what I need to write to have this modify the existing index from the NewsBlog plugin. I don't want to totally exclude it like the error is suggesting, but to subclass it like the documentation says to do. Here is my search_indexes.py file: from aldryn_newsblog.search_indexes import ArticleIndex class BlogHelperIndex(ArticleIndex): def index_queryset(self): # make sure only public posts are pulled return self.get_model().objects.exclude(app_config__app_title='DirectConnection') -
How to add custom preprocessor/postprocessor to django-wiki render?
I am planning to add my custom "syntax extension" to my wiki based on django-wiki (https://github.com/django-wiki/django-wiki). For example I want something like this: {mytemplate param1="value"} to unfold to something like that: <div class="mytemplate"><some_code_that_uses_param1></div> So, how add such custom syntax extension to django-wiki? (I'd prefer to do it without modifying django-wiki's source code) -
Azure Web App for Container can't connect to Azure DB for Postgres
I have a Azure Web App for Containers. I am trying to get the web app to connect to a Azure Database for Postgres. The web app gave me an error "OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?" From the portal, I have granted "Allow access to Azure services" and included all the IPs in the rules. Is there anything I have missed? Thanks. -
What is the default range for IntegerFields on Django?
Such a simple question, but can't seem to find anything in the documentation about it. For example, can integers be negative? -
Heroku migrate: ModuleNotFoundError (suspect issue with static)
I am having an identical problem as here, and here, and here. However, I have attempted the answers given in each of those queries, to no avail. In attempting to deploy an application, from the following command: heroku run python manage.py migrate ERROR ModuleNotFoundError: No module named 'decouple' I suspect that the issue is caused by how I am deploying static. Especially since the command: python manage.py collectstatic returns the following error: FileNotFoundError: [Errno 2] No such file or directory at: '/mnt/project/static/'. Although, it could be an unrelated issue. CODE requirements.txt python-decouple==3.1 settings.py INSTALLED_APPS = [ 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ] PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # The absolute path to the directory where collectstatic will collect static files for deployment STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') PROJECT_PATH = os.path.abspath(os.path.dirname(__name__)) # The URL to use when referring to static files (where they will be served from) STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ROOT_URLCONF = 'mapping_data.urls' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) MEDIA_ROOT = ( BASE_DIR ) STRUCTURE .git __pycache__ htmlcov mapping_data __pycache__ static .keep __init__.py settings.py urls.py wsgi.py mapping_twitter __pyache__ migrations static css β¦ -
kombu.exceptions.EncodeError: TypeError("b'Cannot connect to SMTP
I am trying to send a single email via celery with rabbitmq. The error message I am getting is: kombu.exceptions.EncodeError: TypeError("b'Cannot connect to SMTP 2a00:1450:...::6d>. connect error 10051 ' Is not JSON Serializable. Not sure what's the reason at all. My celery configuration is this: CELERY_BROKER_URL = 'amqp://sam:sem@localhost:5672' CELERY_ENABLE_UTC = True CELERY_RESULT_BACKEND = 'django-db' # Celery Data Format CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' #CELERY_TIMEZONE = 'Africa/Cairo' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' My email function is: @task(name='send_email') def sendEmailMessage(subject,content,rec): email = EmailMessage(subject, content, to=[rec]) email.send() from views.py: sendEmailMessage.delay('welcome','welcome message','email@email.net') -
How does DRF determine the title to show in the browseable API?
I am creating many views with ListAPIView.as_view( queryset=queryset, serializer_class=serializer_class ) The DRF browseable API shows In another project I work on, DRF renders the name of the model class. But that project subclasses ViewSet. Does the browseable API derive the title from the ViewSet or model class in some way? How can I override it with ListAPIView.as_view()? -
Subtraction in django template
I have the following to add two fields together: {{ company.num_licenses|add:company.num_used_licenses }} However, how would I do subtraction? For example: {{ company.num_licenses|add:-company.num_used_licenses }} Is it possible to do the latter, or do I need to write a custom template tag? -
Change value of attribute Django inline formset
I need to change the value of -TOTAL_FORMS to however many fields I add to the formset so that Django will save all of the instances. Relevant portion of form: <div class="form-group"> <div class="input-group-sm"> <label class="text-muted">Approaches</label> <div class="form-control pl-4 pt-2"> {% for formset in inlines %} {{ formset.management_form }} {{ form.id }} {% for form in formset %} <div id="approach_form" class="row"> {{ form.errors }} <div class="col-4 pr-5>">{{ form.approach_type |add_class:"form-control" }}</div> <div class="col-4 pr-5>">{{ form.number |add_class:"form-control" }} </div> <div style="display: none;" class="col pr-5">{% if form.instance.pk %}{{ form.DELETE }}{% endif %}</div> </div> {% endfor %} {% endfor %} </div> </div> </div> JS function call <script src="{% static 'flights/jquery.formset.js' %}"></script> <script type="text/javascript"> $(function() { $('#approach_form').formset({ prefix: '{{ approach_set.prefix }}' }); }) </script> JS script: /** * jQuery Formset 1.3-pre * @author Stanislaus Madueke (stan DOT madueke AT gmail DOT com) * @requires jQuery 1.2.6 or later * * Copyright (c) 2009, Stanislaus Madueke * All rights reserved. * * Licensed under the New BSD License * See: http://www.opensource.org/licenses/bsd-license.php */ ;(function($) { $.fn.formset = function(opts) { var options = $.extend({}, $.fn.formset.defaults, opts), flatExtraClasses = options.extraClasses.join(' '), totalForms = $('#id_' + options.prefix + '-TOTAL_FORMS'), maxForms = $('#id_' + options.prefix + '-MAX_NUM_FORMS'), minForms = $('#id_' + β¦ -
How do I inputs from an HTML page to a script in Django?
I am making a page so that my python script can run using django which requires 3 inputs. In my app I have made a folder where I write and run the HTML commands with 3 inputs and a submit button which works fine. The python script this webpage will run with the three inputs has already been written but I am not sure where to put them or how to pass in the variables after they have been submitted. I am getting a lot of mixed messages telling me to use urls.py, views.py, or make my own utils.py. Should I make a new file for the script or write it in one of the provided files (admin.py, init.py etc)? How can I pass in those values and then have the script run automatically after? Thanks! -
Django testing - wait for subprocess to be ready
I'm using pouchdb-server to create an in-memory database to run my test against with the following code: class CouchdbTestCase(TestCase): def setUp(self): self.proc = subprocess.Popen('pouchdb-server --in-memory', shell=True) time.sleep(1) def tearDown(self): process = psutil.Process(self.proc.pid) for proc in process.children(recursive=True): proc.kill() process.kill() the time.sleep(1) is there as otherwise the tests are ran before the in-memory server is ready Is there a more graceful way to ensure the server is ready without having to do such a long wait? -
Query to check if parent data is associated with unrelated data through a lookup table
Sorry for the confusing title. If someone can suggest, please do. I have this 4 models: Parent() Child(): parent= models.ForeignKey(Parent,related_name='parent_child') Member() MemberChild(): member= models.ForeignKey(Member, related_name='member_child') child = models.ForeignKey(Child, related_name='child_member') Now, what I want is to list all parents and see if they are in use by the logged in member. Sample Data: Parent 1 Parent1 2 Parent2 Child 1 1 Child1 Member 1 Member1 MemberChild id child member 1 1 1 Now the expected output is (for member id 1): Parent1 True Parent2 False in which True means any Child of parent1 is currently being used by the member. -
Angular - Django: login and display data from database
I am able to log in and able to display the name of the user, I want to display the data of that particular user on the profile page. login.component.ts import { Component, OnInit } from '@angular/core'; import {BlogPostService} from '../blog_post.service'; import {UserService} from '../user.service'; import {throwError} from 'rxjs'; // Angular 6/RxJS 6 import {Router} from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { public user: any; /** * An array of all the BlogPost objects from the API */ public posts; /** * An object representing the data in the "add" form */ public new_post: any; constructor( private _userService: UserService, private router: Router) { } ngOnInit() { this.getPosts(); this.new_post = {}; this.user = { username: '', password: '' }; } login() { this._userService.login({'username': this.user.username, 'password': this.user.password}); this.router.navigateByUrl('/profile'); } refreshToken() { this._userService.refreshToken(); } logout() { this._userService.logout(); } } Login.component.html <h2>Log In</h2> <div class="row" *ngIf="!_userService.token"> <div class="col-sm-4"> <label>Username:</label><br /> <input type="text" name="login-username" [(ngModel)]="user.username"> <span *ngFor="let error of _userService.errors.username"><br />{{ error }}</span></div> <div class="col-sm-4"> <label>Password:</label><br /> <input type="password" name="login-password" [(ngModel)]="user.password"> <span *ngFor="let error of _userService.errors.password"><br />{{ error }}</span> </div> <div class="col-sm-4"> <button (click)="login()" class="btn btn-primary">Log In</button>&nbsp; </div> <div class="col-sm-12"> <span *ngFor="let error of _userService.errors.non_field_errors">{{ error β¦ -
submit does not work on django 2.1 model form rendered manually with updateview
totally a new to django. I have a modelform and have manually rendered it using the form fields so that I can use it with my CSS , however, form.as_p if used seems to save my data, if I use the manual form rendering and submit, nothing saves and wanted to know 1) why the form.as_p works and my custom form fields will not work 2) the update view class , does it require the post method? class CompanyUpdateView(UpdateView): template_name = 'inservice/company_update.html' form_class = CompanyForm model = CompanyInfo def get_object(self): pk_=self.kwargs.get("pk") return get_object_or_404(CompanyInfo,pk=pk_) company_update.html <form method="POST" action=""> {% csrf_token %} <div class="container-fluid"> <div class ="row mb-5"> <div class="col"> <div class="custdiv"> <hr> <h3>Company Information</h3> <hr> <table class="table table-hover table-striped"> <tr> <td>Company Name:</td> <td>{{form.companyname}}</td> </tr> <tr> <td>Phone:</td> <td> {{form.phone}} </td> </tr> <tr> <td>Total Veh:</td> <td>{{form.numberofcars}}</td> </tr> <tr> <td>Status:</td> <td>{{form.status}}</td> </tr> <tr> <td>Address: </td> <td>{{form.address}}</td> </tr> <tr> <td>Unit: </td> <td>{{form.unitno}}</td> </tr> <tr> <td>City:</td> <td>{{form.city}}</td> </tr> <tr> <td>Province: </td> <td>{{form.provincestate}}</td> </tr> <tr> <td>Country: </td> <td>{{form.country}}</td> </tr> <tr> <td>Postal/Zip</td> <td>{{form.postalcode}} </td> </tr> </table> enter code here </div> </div> <div class="col"> <div class="custdiv"> <hr aria-colcount="1"> <h3>System Information</h3> <hr> <table class="table table-hover table-striped"> <tr> <td>XDS Version</td> <td>{{form.xdsversion}}</td> </tr> <tr> <td>CallBack Version</td> <td>{{form.callbackversion}}</td> </tr> <tr> <td>SMS Version</td> <td>{{form.smsversion}}</td> β¦ -
Automize a task of DetailView
I have in my models.py 2 model (table) factures and typeFact I want to have a list of factures for every TypeFact I realized it but I have to enter the key, example : http://127.0.0.1:8000/TasksManager/typefact/2/ I want to automize it by choose the type in listchoice, I have to modify my code and I need your help : views.py class TypeFact_detail_factures(DetailView): model = TypeFact template_name = 'TypeFact_detail_factures.html' def get_context_data(self, **kwargs): context = super(TypeFact_detail_factures, self).get_context_data(**kwargs) tasks_dev = Factures.objects.filter(type_fact=self.object) # champs de liaison context['tasks_dev'] = tasks_dev return context the HTML correspondent url path('typefact//', views.TypeFact_detail_factures.as_view(), name='typefact'), I want to replace automatically pk automatically by it correspondent in the model typefact thanks -
Uwsgi on centos6 giving Illegal seek [proto/uwsgi.c line 40]
i am trying to deploy my django project with uwsgi and nginx, when i run uwsgi --socket :8001 -b 32000 --module landivarpj.wsgi & i load the website page and i get a problem in uwsgi *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** *** uWSGI is running in multiple interpreter mode *** spawned uWSGI worker 1 (and the only) (pid: 14076, cores: 1) uwsgi_proto_uwsgi_parser(): Illegal seek [proto/uwsgi.c line 40] anyone know how to fix this ? ps. im running it in a virtual env using python 3.4.8(python3) my nginx/conf.d/uwsgi.conf server { listen 80; server_name drlandivar.com www.drlandivar.com; location / { include uwsgi_params; uwsgi_pass unix:/var/tmp/uwsgi.sock; } } my sites-available(site availa is sym with site-enable) ### example.conf nginx configuration # the upstream component nginx needs to connect to upstream django { server 192.254.145.207:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 80; # the domain name used for the test, replace it with your own domain. server_name drlandivar.com www.drlandivar.com; # the default charset charset utf-8; # Set max upload size client_max_body_size 100M; # adjust according to your β¦ -
Filter django for objects containing subsets of same many to many relationship
In my database I have user objects with two many to many fields (messages and following) on them that both contain a many to many field related to another object Topic. I want to filter for all "users" who have "messages" attached to them that do not contain all of the topics attached to the "following" objects on the user. Right now I am useing a loop to accomplish this: users = set() for user in User.objects.filter(messages__isnull=False, following__isnull=False).iterator(): if not set(user.messages.values_list('topics', flat=True) ).issubset(set(user.following.values_list('topics', flat=True))): users.add(user.pk) Is there a way to accomplish the same thing with a single query? I've tried variations of annotate, aggregate, and F() queries but I wasn't able to accomplish what I'm looking for.