Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python manage.py runserver in Docker container not working
Inside my Docker container, in the root folder of my Django application, I activate a virtual environment, and run python manage.py runserver. I have exposed the ports 80 and 443 for the container, and at first glance it appears to be running >>> docker run -it <container> >>> cd .virtualenv >>> source bin/activate >>> cd .. >>> python manage.py runserver System check identified no issues (0 silenced). February 20, 2018 - 20:32:08 Django version 1.11.6, using settings 'sesttings.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. When I go to http://:8000 though the site can't be accessed, it just sits there and loads forever. I checked the logs using docker logs container_id, but there isn't anything in there. -
Upon stripe customer creation save Customer model on server
The stripe customer is being successfully created on stripes servers but I need a representation on my server so I created the Customer model all it has is the user_id and the stripe_id. Heres the code I have been trying but it does not work.. I think the problem is with retrieving the actual stripe id for that particular user.. # Create stripe customer stripe.Customer.create() new_customer = Customer( user=request.user, stripe_id=id, ) new_customer.save() This snippet of code is inside the user registration view, and it runs after the user is authenticated and logged in So what appears in the stripe_id field is: <built-in function id> -
Nginx serving Django in subdirectory - admin login is redirecting
I have to serve a Django app from a subdirectory (hostname/service/). So far I'm able to get to the Admin Login prompt (hostname/service/admin/login/), but after successfully logging in I'm redirected to (hostname/admin/login/) and get a 404. How can I keep the correct subdirectory and get inside the Admin panel? Here's the nginx.conf server block: server { listen 80; root /usr/share/nginx/html/; charset utf-8; location /service { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://djangoapp:8000/; proxy_set_header X-Real-IP $remote_addr; } location /static { alias /usr/src/app/static; } } -
Why do I lose connectivity to my SQL server when running through Apache?
I am trying to deploy my django project on my company LAN. I am able to get the site working, however, I lose connectivity to my Microsoft SQL Server when I run site through apache. Everything works fine in the development environment. I suspect it I am losing windows authentication when I work through the apache server. This is what my db settings are in my settings.py files: 'mosaiq': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'MOSAIQ', 'USER': '', 'PASSWORD': '', 'HOST': 'HHCMOSAIQ01T', 'PORT': '', 'OPTIONS': {'driver': 'ODBC Driver 11 for SQL Server', }, Any ideas how to connect to my sql server using windows authentication or does my problem lie elsewhere? -
Delete/Clear staticfiles cache in whitenoise
I cant seem to find how to refresh the whitenoise static files cache. It has been giving me a problem. Which has persisted even when I removed the specific file cause the problem. The Manifest is still referring to a missing removed staticfile. I would like to clear the cache so that it can be repopulated. -
multiple paginations in Django not working, getting redirected
I am struggling with this for a while now and I came close to something. I have four models bound to each other by foreign keys in this order: Faculty > Department > StudyProgramme > Courses. I created pagination with search for all of my courses. Now I wanted to create pagination for courses that belong to a specific faculty only. For example, I have a total of 3 courses, from which 2 belong to Informatics faculty and 1 belongs to Medicine faculty, and for each of those I need pagination by 1 course per page. After a lot of tries, I thought of using faculties id's as a way to make individual pagination, but no success.. All courses of a faculty get displayed, instead of just 1, and if I click next, I get redirected to the pagination of all courses. I don't know how to fix this: @login_required def index(request): query_list = Course.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(name__icontains=query)) paginator = Paginator(query_list, 1) page = request.GET.get('page') faculty_id = request.GET.get('faculty_id') courses_to_display = None try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) if not faculty_id: courses_to_display = courses faculties = Faculty.objects.all() for … -
How to get a specific row by using the row number
I'm trying to make a function that will find the median value of a set. However, I don't know how to filter the queryset by row number. Code: Function: def getQuestion(attr): datatype = Attribute.objects.filter(attribute_name = attr).values('attribute_data_type') if datatype == 'BOOLEAN': return 'Is the object ' + attr + '?' if datatype == 'DOUBLE': temp = Object_Attribute.objects.filter(attribute_name = attr).order_by('attribute_double') hw = int hw = Object_Attribute.objects.filter(attribute_name = attr).count()/2 par return par Models: class Object(models.Model): object_number = models.IntegerField() object_name = models.CharField(max_length=200) def __str__(self): return self.object_name class Attribute(models.Model): attribute_number = models.IntegerField() attribute_name = models.CharField(max_length=200) attribute_data_type = models.CharField(max_length=200) attribute_range_low = models.DecimalField(max_digits=100, decimal_places=50, null=True, blank=True) attribute_range_high = models.DecimalField(max_digits=100, decimal_places=50, null=True, blank=True) def __str__(self): return self.attribute_name class Object_Attribute(models.Model): object_name = models.ForeignKey('Object', on_delete=models.CASCADE) attribute_name = models.ForeignKey('Attribute', on_delete=models.CASCADE) attribute_boolean = models.NullBooleanField(null=True, blank=True) attribute_double = models.FloatField(null=True, blank=True) attribute_string = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return str(self.object_name) +'\'s ' + str(self.attribute_name) -
Project runs on Heroku locally, but not online
I was deploying my project to Heroku and tried locally with the te comand heroku local web. That works perfectly, but, when I sended the the project to run online, I got this error on Heroku logs: 2018-02-20T17:23:21.824637+00:00 heroku[web.1]: State changed from starting to crashed 2018-02-20T17:23:33.111420+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sagaedu.herokuapp.com request_id=b04299fc-6ea8-41d3-a994-9a064b6d98af fwd="177.39.172.28" dyno= connect= service= status=503 bytes= protocol=https 2018-02-20T17:24:03.282786+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sagaedu.herokuapp.com request_id=88a02575-95dc-4450-b9b4-e53f65770454 fwd="177.39.172.28" dyno= connect= service= status=503 bytes= protocol=https 2018-02-20T17:27:04.669222+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sagaedu.herokuapp.com request_id=c56fa212-d104-4569-b916-439e3d003398 fwd="177.39.172.28" dyno= connect= service= status=503 bytes= protocol=https 2018-02-20T17:32:00.954709+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sagaedu.herokuapp.com request_id=c8126dd0-0868-4d12-9421-2d2d7b94e73c fwd="177.39.172.28" dyno= connect= service= status=503 bytes= protocol=https 2018-02-20T17:35:16.000000+00:00 app[api]: Build started by user 2018-02-20T17:36:00.992071+00:00 heroku[web.1]: State changed from crashed to down 2018-02-20T17:36:00.794498+00:00 app[api]: Deploy 07a1f9df by user 2018-02-20T17:36:00.794498+00:00 app[api]: Release v15 created by user 2018-02-20T17:35:16.000000+00:00 app[api]: Build succeeded 2018-02-20T17:38:16.055964+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=sagaedu.herokuapp.com request_id=12e85de9-ac80-413c-b022-8f8fb91944aa fwd="177.39.172.28" dyno= connect= service= status=503 bytes= protocol=https -
django distinct in the ListViews
I am having an issue with a distinct in the ListViews I have a connection M2M between “Allergeni” and “Ingredient” and another one M2M between “Product” and “Ingredient” that goes through the table “Materiali”. I need to obtain a table with the whole list of “Product” with an extra field “Allergeni” that contains only a unique version for of all the values in the raw model for ingredients: class Ingredient (models.Model): nome = models.CharField(max_length=200) categoria = models.ForeignKey("Categoria") costokg = models.DecimalField(max_digits=20,decimal_places=2,default=Decimal('0.00')) resa = models.IntegerField() prezzopulito = models.DecimalField(max_digits=20,decimal_places=3,default=Decimal('0.00')) componenti = models.TextField() allergeni = models.ManyToManyField("Allergeni", blank=True) def __str__(self): return self.nome def get_absolute_url(self): return reverse("ingredients:detail", kwargs={"pk": self.pk}) class Allergeni (models.Model): allergene = models.CharField(max_length=100) model for products: class Product (models.Model): nome = models.CharField(max_length=250) descrizione = models.TextField(blank=True, null=True) prezzo = models.DecimalField(max_digits=20,decimal_places=2,default=Decimal('0.00')) peso_finale = models.DecimalField(max_digits=20,decimal_places=2,default=Decimal('0.00')) categoria = models.ForeignKey("Categoria") tag = models.ManyToManyField("Tag", blank=True) componenti = models.ManyToManyField(Ingredient, through='Materiali', through_fields=('object_id', 'ingrediente')) creazione = models.DateTimeField(auto_now=False, auto_now_add=True) aggiornamento = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return self.nome def get_absolute_url(self): return reverse("products:detail", kwargs={"pk": self.pk}) class Materiali (models.Model): object_id = models.ForeignKey("Product", on_delete=models.CASCADE) ingrediente = models.ForeignKey(Ingredient, on_delete=models.CASCADE, related_name="materia_prima") peso = models.DecimalField(max_digits=20,decimal_places=2,default=Decimal('0.00')) def __str__(self): return self.ingrediente.nome product view def product_list(request): queryset = Product.objects.all() \ .annotate(total=Round((Sum((F('materiali__ingrediente__prezzopulito')/1000) * F('materiali__peso'))) / (F('peso_finale'))) * 1000 ) materiali = Materiali.objects.all() allergeni= materiali.values_list('ingrediente__allergeni__allergene', flat=True).distinct() … -
Trouble rendering Images through Django templates using static tags and view.py request
I am trying to dynamically add images to my web page using Django templates. If is add the image name directly, the image is on the web page as expected: {% block content %} {% load staticfiles %} <img id='productImage' src="{% static 'buylist/img/images/image name.jpg' %}"> {% endblock %} instead of passing the name of the file directly, I want to pass the file name using my the name of the product in my database like: <img id='productImage' src="{% static 'buylist/img/images/{{product.name}}.jpg' %}"> But I guess I can't use template tags inside of static tags? When I do it this way and inspect the element on the webpage, I see that it rendered{{product.name}} as pure text, so of course it didn't find the image. I also tried including the file name in my database directly as an attribute of my product like: <img id='productImage' src="{% static 'buylist/img/images/{{product.image}}' %}"> There was still no image where I would expect one, but when I inspected the element on the page it had the correct filename image name.jpg. I don't know too much about html, but this led me to believe there was some sort of problem with my directory settings. I tried including in my … -
Why my form input of type number is not getting any value?
pleease help. I am trying to get the value of the input with id amount_0027634199476. Whenever I change the value of the field, I am not getting anything through javascript after I click on the submit button which is supposed to send an alert with the input box's value. This is my code: <div class="modal-body"> <form id="frm_entry_0027634199476" method="post"> <input type='hidden' name='csrfmiddlewaretoken' value='a9wl1mTYjT1FhTmhr41zLoy6H7ay4QPvDXQHuUSNcGcMkrUNVISM7BSvRbVp3RPf' /> <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12">Montant</label> <div class="col-md-9 col-sm-9 col-xs-12"> <input type="number" id="amount_0027634199476" class="form-control"> </div> </div> <div class="form-group"> <div class="col-md-9 col-sm-9 col-xs-12"> <div class="radio"> <label> <input type="radio" checked="" value="True" id="optionsRadios1" name="deposit_0027634199476"> <strong>Depot</strong> </label> </div> <div class="radio"> <label> <input type="radio" value="False" id="optionsRadios2" name="deposit_0027634199476"> <strong>Retrait</strong> </label> </div> </div> </div> </form> </div> <div class="modal-footer"> <button type="cancel" class="btn btn-primary" data-dismiss="modal">anuller</button> <button type="submit" class="btn btn-default" onclick="submiter()" >valider</button> <script> function submiter(){ x = document.getElementById("amount_0027634199476"); alert(x.value); } </script> Am I doing something wrong? How can I right it? -
Django nested dictionary to display in templates
I have a dictionary that looks like this dict = { 'https://i.redd.it/4d87ifm2mch01.jpg': 'https://reddit.com/7yv1d8', 'https://i.redd.it/ru0bq0jpr9h01.jpg': 'https://reddit.com/7ys0l3', 'videos': {'https://gfycat.com/ifr/selfassuredinfinitehochstettersfrog'},.. } 'videos' stores values as a set so i wont have duplicate urls and it's convenient. But i faced a problem, how can I display the nested dictionary in templates? I have it like that for now {% for keys,values in data.items%} {% for i,j in keys.items %} <iframe src='{{j}}' frameborder='0' scrolling='no' allowfullscreen width='300' height='300'></iframe> <a class="thumbnail" href="{{values}}"><img src="{{keys}}" width="100px" height="66px" border="1" /><span><img src="{{keys}}" /><br />whatever.</span></a> <br /> I want the 'videos' values to be stored in the <iframe> and others as an image. -
Testing and mocking a threaded function within a view
I'm trying to unit test a function that I run threaded within a view. Whenever I try to mock it, it always goes to the original function, no the mocked function. The code I'm testing, from the view module: def restart_process(request): batch_name = request.POST.get("batch_name", "") if batch_name: try: batch = models.Batch.objects.get(num=batch_name) except models.Batch.DoesNotExist: logger.warning("Trying to restart a batch that does not exist: " + batch_name) return HttpResponse(404) else: logger.info(batch_name + " restarted") try: t = threading.Thread(target=restart_from_last_completed_state, args=(batch,)) t.daemon = True t.start() except RuntimeError: return HttpResponse(500, "Threading error") return HttpResponse(200) else: return HttpResponse(400) The test function: class ThreadTestCases(TransactionTestCase): def test_restart_process(self): client = Client() mock_restart_from_last_completed_state = mock.Mock() with mock.patch("processapp.views.restart_from_last_completed_state", mock_restart_from_last_completed_state): response = client.post('/batch/restart/', {"batch_name": "BATCH555"}) self.assertEqual(response.status_code, 200) mock_restart_from_last_completed_state.assert_called_once() The URL: url(r'^batch/restart/$', views.restart_from_last_completed_state, name="restart_batch"), I always get this error: ValueError: The view processapp.processing.process_runner.restart_from_last_completed_state didn't return an HttpResponse object. It returned None instead. I put a print command in the original function (restart_from_last_completed_state) and it always runs so the mocking does not take place. The error seems to take the function as a view although it is not. I'm not sure where the error is, the threading, testing, something else? -
Unable to import a model in another app
I am working in Django 1.8 and Python 3.5 I have 3 apps -> mainpage,login,signup and the directory is given in the picture I am trying to import mainpage/models.py in login/forms.py But when I do it it give If there is anything else you people want me to post tell me what do I do in the comments ? See Image and yes Please I have read this already but not working.Thanks in advance TRACEBACK Environment: Request Method: GET Request URL: http://localhost:8000/login Django Version: 1.8 Python Version: 3.5.4 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainpage', 'signup', 'login', 'rest_framework', 'corsheaders') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in get_response 108. response = middleware_method(request) File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\site-packages\django\middleware\common.py" in process_request 74. if (not urlresolvers.is_valid_path(request.path_info, urlconf) and File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\urlresolvers.py" in is_valid_path 647. resolve(path, urlconf) File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\urlresolvers.py" in resolve 522. return get_resolver(urlconf).resolve(path) File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\urlresolvers.py" in resolve 368. sub_match = pattern.resolve(new_path) File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\urlresolvers.py" in resolve 240. return ResolverMatch(self.callback, args, kwargs, self.name) File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\urlresolvers.py" in callback 247. self._callback = get_callable(self._callback_str) File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\urlresolvers.py" in get_callable 106. mod = import_module(mod_name) File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py" in import_module 126. return _bootstrap._gcd_import(name[level:], package, level) File "C:\Users\vaibhav2\PycharmProjects\MajorProject\src\login\views.py" in <module> 2. from .forms import UserLoginForm File "C:\Users\vaibhav2\PycharmProjects\MajorProject\src\login\forms.py" in … -
How Prepare the database for SALEOR
Prepare the database for SALEOR: $ python manage.py migrate This command will need to be able to create database extensions. If you get an error related to the CREATE EXTENSION command please review the notes from the user creation step. # python3 manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 216, in fetch_command klass = load_command_class(app_name, subcommand) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/migrate.py", line 12, in <module> from django.db.migrations.autodetector import MigrationAutodetector File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/autodetector.py", line 11, in <module> from django.db.migrations.questioner import MigrationQuestioner File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/questioner.py", line 9, in <module> from .loader import MigrationLoader File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/loader.py", line 8, in <module> from django.db.migrations.recorder import MigrationRecorder File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/recorder.py", line 9, in <module> class MigrationRecorder: File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/recorder.py", line 22, in MigrationRecorder class Migration(models.Model): … -
How to create a dynamic model-form?
I'm new to Django and I'm trying to write a project where employers can post job vacancies. I want to be able to save the job description as a model using a model-form but I also want to allow the user to specify how many requirements there are for a job. So one job might specify 4 job requirements while another might specify 6. So saved models will vary depending on how much requirements were specified. Is there anyway to create a dynamic model-form where the user can specify how many fields there are in the form and model? I've been researching this for a while but yet to find a simple explanation. -
django model saving the data temporary
I am using postgresql as database and it is just saving the data permanently into the database. So, given below is my views.py file @login_required def add_comment(request): if request.method == 'POST': comment = request.POST.get('comment') floor_id = request.POST.get('floor_id') question_id = request.POST.get('question_id') floor_detail = get_object_or_404(FloorDetail, id=floor_id) question = get_object_or_404(Question, id=question_id) answer, created = Answer.objects.get_or_create(floor_no=floor_detail, question=question) comment_obj = Comment.objects.create(answer=answer, comment=comment) print(answer, comment_obj) data = render(request,'mobile/include/single_comment.html', {'comment':comment_obj}) if data: html=data else: html=None return HttpResponse(html) else: question_id = request.GET.get('question_id') floor_id = request.GET.get('floor_id') question = get_object_or_404(Question, id=question_id) floor_detail = get_object_or_404(FloorDetail, id=floor_id) answer = Answer.objects.filter(floor_no=floor_detail, question=question).first() comments = Comment.objects.filter(answer=answer) data = render(request,'mobile/include/comment.html', {'comments':comments}) if data: html=data else: html=None return HttpResponse(html) when i use print (answer, comment_obj) statement it is printing out both the objects on the terminal, however when check the database through django-admin interface the answer & comment_obj instance isn't shown, means data is not reflected there. Please tell me how to fix it. -
django - view for redirecting to another page with query recieved
I have two search inputs, first on home page another on search results itself. what i m try to do is receive query form home and redirect it to search results page according to this : Like I search - html-5 redirect page should be - 127.0.0.1/html-5/find/?q=html-5 I have tried but unfortunately not getting the right way to it, please suggest me the correct way to do it. -
Combining ModelAdmin and InlineModelAdmin
Given two models Group and Member, where Member has a foreign key to Group: class Group(models.Model): # some fields class Member(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) # some other fields how can I have both a custom ModelAdmin for Member as well as an InlineModelAdmin (of members) in Group? class MemberAdmin(admin.ModelAdmin): # some logic, restricting fields, changing change form initial data.... admin.site.register(Member, MemberAdmin) class GroupAdmin(admin.ModelAdmin): # some logic, restricting fields, changing change form initial data.... inlines = [<MemberInline>] admin.site.register(Group, GroupAdmin) Adding a new inline admin for Member ignores the custom logic in its admin class class MemberInline(admin.TabularInline): model = Member extra = 3 # Does not respect the custom logic in MemberAdmin -
Error in Virtualenv(Python3.5/pip3/Django2.0/psycopg2) when run python3 manage.py migrate
I can run manage.py migrate at Virtualenv(Python3.5/pip3/Django2.0/psycopg2). (miWeb) xxxx@yyyy:~/myproject/miWeb$ python3 manage.py migrate /home/xxxx/mipagina/lib/python3.5/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 58, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/xxxx/miWeb/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File … -
django checkbox unchecked despite initial=True
I have a Django form containing a boolean field, "reduction." The field has an initial value of True (i.e. I want the corresponding checkbox to render as checked). My problem is that this doesn't happen. When the form first renders, the checkbox is unchecked. Searching for this topic yields a ton of issues related to the value of the checkbox on submit, and how it doesn't send anything if unchecked, etc. But I can't figure out why Django isn't initially checking this box. I've verified that the value of the field in the form is indeed true when the form is passed to the template from the view. Any ideas? The Form: class RunParamsForm(Form): fluid_present = BooleanField(widget=HiddenInput, required=False) solid_init_present = BooleanField(widget=HiddenInput, required=False) solid_sim_present = BooleanField(widget=HiddenInput, required=False) solid_present = BooleanField(widget=HiddenInput, required=False) load_map_present = BooleanField(widget=HiddenInput, required=False) scallop_map_present = BooleanField(widget=HiddenInput, required=False) fluid_endtim_units = CharField(widget=TextInput(attrs={'class': 'units', 'readonly': 'readonly'})) solid_init_drterm_units = CharField(widget=TextInput(attrs={'class': 'units', 'readonly': 'readonly'})) solid_sim_endtim_units = CharField(widget=TextInput(attrs={'class': 'units', 'readonly': 'readonly'})) steps = CharField(widget=HiddenInput) reduction = BooleanField(initial=True, required=False) The relevant html: <!-- REDUCTION BLOCK --> <div class="block1"> <div class="queueRunHeading"> Other </div> <div class="fieldWrapper"> <label for="{{ form.reduction.id_for_label }}"> 1-Dimensional Reduction </label> {{ form.reduction }} <span class="errorlist"> {{ form.reduction.errors.as_text }} </span> </div> </div> -
LookupError: No installed app with label 'app' (Django 1.11 / Python 2.7 / xadmin)
Can't for the life of me figure out what the issue is. Help please! I'm trying to extend the admin view (using the xadmin app), by including a chart The issue started appearing with the addition of: admin from xadmin import views from .models import DGISummary ... @xadmin.sites.register(views.website.IndexView) class MainDashboard(object): widgets = [ [ { "type": "chart", "model": "dgisummary", "chart": "reg_members", "params": { "_p_date__gte": "2017-01-01", "p": 1, "_p_date__lt": "2017-12-01" } }, ], ] model @python_2_unicode_compatible class DGISummary(models.Model): quarter = models.CharField(max_length=2,) reg_members = models.IntegerField() sub_received = models.IntegerField() ... class Meta: verbose_name = u"Summary" verbose_name_plural = verbose_name def __str__(self): return self.quarter And the traceback System check identified no issues (0 silenced). February 20, 2018 - 15:38:35 Django version 1.11.10, using settings 'csa_portal.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. ERROR:root:No installed app with label 'app'. Traceback (most recent call last): File "C:/../apps\xadmin\views\dashboard.py", line 563, in get_widgets ws.append(self.get_widget(widget)) File "C:/../apps\xadmin\views\base.py", line 78, in method return filter_chain(filters, len(filters) - 1, _inner_method, *args, **kwargs) File "C:/../apps\xadmin\views\base.py", line 47, in filter_chain return func() File "C:/../apps\xadmin\views\base.py", line 72, in _inner_method return func(self, *args, **kwargs) File "C:/../apps\xadmin\views\dashboard.py", line 517, in get_widget wid_instance = widget_with_perm(self, data or widget.get_value()) File "C:/../apps\xadmin\views\dashboard.py", line 325, in __init__ super(ModelBaseWidget, self).__init__(dashboard, … -
Optimise Django query with large subquery
I have a database containing Profile and Relationship models. I haven't explicitly linked them in the models (because they are third party IDs and they may not yet exist in both tables), but the source and target fields map to one or more Profile objects via the id field: class Profile(models.Model): id = models.BigIntegerField(primary_key=True) handle = models.CharField(max_length=100) class Relationship(models.Model): id = models.AutoField(primary_key=True) source = models.BigIntegerField(db_index=True) target = models.BigIntegerField(db_index=True) My query needs to get a list of 100 values from the Relationship.source column which don't yet exist as a Profile.id. This list will then be used to collect the necessary data from the third party. The query below works, but as the table grows (10m+), the SubQuery is getting very large and slow. Any recommendations for how to optimise this? Backend is PostgreSQL but I'd like to use native Django ORM if possible. user = Profile.objects.get(handle="philsheard") qs_existing_profiles = Profiles.objects.all() rels = TwitterRelationship.objects.filter( target=user.id, ).exclude( source__in=Subquery(qs_existing_profiles.values("id")) ).values_list( "source", flat=True ) Thanks in advance for any advice! -
Relative URL replace part of old url instead of add to old one in django
i have a problem with relative url in django application. i have structure of objects which look like this Competitions/ games/ players/ costs/ and urls to point to it competitions/ list of all competitions {% for comp in competitions%} <li onclick=window.location.href='{{comp.pk}}'> comp.name </li> {% endfor %} when i clik on one of this links im redirect to page competitions/ competitions/ detail view of a competition competitions/games/ list of all game in picked competition {% for game in games%} <li onclick=window.location.href='{{game.pk}}'> game.name </li> {% endfor %} so when im on url: competitions/games/1 which list all games in competition with id = 1 <li onclick=window.location.href='1'> game1</li> <li onclick=window.location.href='2'> game2</li> <li onclick=window.location.href='3'> game3</li> <li onclick=window.location.href='4'> game4</li> and i click for example on game4 my url address is competitions/games/4 insted of competitions/games/1/4 can someone explain me why. -
Django Deploy to Heroku "Six" / "django-appconf" issue
I am a complete beginner, but I have created a small website using Python / Django with the help of django-cookiecutter, including the deploy to Heroku instructions. I am in the process of deploying it for the first time to Heroku, however, the build is failing at the point in which it is running setup.py install for django-appconf, suggesting that it is due to the fact that Heroku already has the "Six" package. The error message I am receiving is as follows: Running setup.py install for django-appconf: finished with status 'error' Complete output from command /app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-tzjhtkga/django-appconf/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-y2i8uuc4-record/install-record.txt --single-version-externally-managed --compile --without-c-extensions: usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: option --without-c-extensions not recognized ---------------------------------------- Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-tzjhtkga/django-appconf/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-y2i8uuc4-record/install-record.txt --single-version-externally-managed --compile --without-c-extensions" failed with error code 1 in /tmp/pip-build-tzjhtkga/django-appconf/ ! Hello! Your requirements.txt file contains the six package. ! This library is automatically installed by Heroku and shouldn't be in ! Your requirements.txt file. This can cause unexpected behavior. ! -- Much Love, Heroku. ! …