Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset with multiple m2m fields
I have these models: class Doctor(models.Model): coopsort = ManyToManyField('Cooperation', related_name='coopsort') name = models.CharField(...) class Cooperation(models.Model): doctor = models.ManyToManyField(Doctor, blank=True, verbose_name=u"Doc") How can I query all Cooperations for a given doctor using the coopsort m2m field? Cooperation.objects.filter... <pls advise here> -
django issues between forms and models
i am a beginner with Django. I want to ask how can i access a variable in forms.py to print out for the user. I know that models.py create the database for the user. The variable that i want to print it is a checkbox multiple choice field. I need to print the value of the multiplechoice in a table.The image is here Forms.py: market = forms.MultipleChoiceField(required=False,widget=CheckboxSelectMultiple, choices=MARKET_CHOICES) sector = forms.MultipleChoiceField(required=False,widget=CheckboxSelectMultiple, choices= MEDIA_CHOICES) I want to print in the html template these two variables Models.py: class Parameters(models.Model): user = models.ForeignKey(User) title = models.CharField('title', max_length=100, default='', blank=True, help_text='Use an indicative name, related to the chosen parameters') type = models.CharField('forecast type', choices=FORECAST_TYPES, max_length=20, default="backtest") #input characteristics price_1_min = models.FloatField('1. Price, min', default=0.1, validators=[MinValueValidator(0.1), MaxValueValidator(20000)]) price_1_max = models.FloatField('1. Price, max', default=20000, validators=[MinValueValidator(0.1), MaxValueValidator(20000)]) -
PLS-00201 identifier 'PACKAGENAME.PROCEDURENAME' must be declared
iam working on the Backend of a Chat System, used whit Django Server. I wrote an procedure in SQL-Developer for the Oracle Database, which should provide the recent messages to an endpoint. When i run the Procedure in SQL-Developer it goes smoothly. But if i run the Procedure in the endpoint, there is following Error-Message: b'{"ERROR_NO": 6550, "ERROR_MSG": "ORA-06550: line 1, column 7:\\nPLS-00201: identifier \'P_CHAT.GET_MESSAGES\' must be declared\\nORA-06550: line 1, column 7:\\nPL/SQL: Statement ignored\\n"}' Views.py #getmessage @need_get_parameters([PARAM_SENDING_USER_ID, PARAM_LAST_ID]) def get(self, request, *args, **kwargs): uid = request.GET.get(PARAM_SENDING_USER_ID) last_id = request.GET.get(PARAM_LAST_ID) #ToDo validate Data try: params = {"i_lastId": last_id} results = db_execute_procedure_ajax_response("p_chat.get_messages", params, uid) return HttpResponse(json.dumps(results)) except Exception as a: return HttpResponse(error_json(ERR_MSG_NO_RECENT_MESSAGE)) Selfmade db.py Method (Works on all the other Endpoints) @trace_db_ajax def db_execute_procedure_ajax_response(procedure_name, params, uid): params["o_data"] = {"type": cx_Oracle.CLOB} try: rparams = db_execute_procedure_lro(procedure_name, params, uid) except DBExecuteLogicalException as e: return ajax_response_bad_request(error_response(e.error_code, e.error_msg, e.error_info)) except DBExecutePhysicalException as e: return ajax_response_server_error(error_response(e.error_code, e.error_msg)) return ajax_response(rparams["o_data"]) Procedure create or replace PACKAGE BODY P_CHAT AS PROCEDURE get_messages ( i_userId in number, i_lastId in number, o_retCode out number, o_json out clob )IS m_retCode number := STD_C.retCode_ok; BEGIN apex_json.initialize_clob_output; apex_json.open_array(); if i_userId IS NULL then m_retCode := STD.error(P_C.ERR_USER_ID_MISSING); else for cs in( SELECT id, message, sender_id, gendate FROM … -
Django: understanding .values() and .values_list() use cases
I'm having trouble understanding under what circumstances are .values() or .values_list() better than just using Model instances? I think the following are all equivalent: results = SomeModel.objects.all() for result in results: print(result.some_field) results = SomeModel.objects.all().values() for result in results: print(result['some_field']) results = SomeModel.objects.all().values_list() for some_field, another_field in results: print(some_field) obviously these are stupid examples, could anyone point out a good reason for using .values() / .values_list() over just using Model instances directly? -
Django REST views: return images without models
I am completely new to Django REST, and I have been wasting time googling for a way to accomplish something that does not seem to be excessively difficult. I want to define a view using the Django predefined classes for views. This view should return an image (given its name), so a URL like this would return the image example.png: http://localhost:8000/api/v1/image/example.png However I do not want this image to be stored in a model (it would be stored in the server as a png file). The class rest_framework.generics.RetrieveAPIView seems to suit my needs, as I can set permissions and authentication classes to restrict the access to the images, but I cannot figure out how to set the queryset if I do not have a model with my images. Any ideas on this? Thanks and forgive my ignorance. -
Djangot test freeze in thread while saving model
when i try test django my test is hanging. Django 1.9.6 code that run in thread def _take_snapshot(self, host, path): # some actions # ... return super(MyClass, self).take_snapshot(host, path) def thread_snapshot(self, host, path): pool = ThreadPool(processes=1) # speacial 1 proc version = pool.apply(self._take_snapshot, (host, path)) pool.close() pool.join() def take_snapshot(self, host, path): # hang here Version.objects.create(client_type, host, path) -
Trying to translate `English` text to different languages using `py-translate`. Getting Error:
I have list of words in a csv file. I am converting that words in different languages. I am trying to use py-translate unfortunately i am getting the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Python/2.7/site-packages/translate/__init__.py", line 10, in <module> from .coroutines import * File "/Library/Python/2.7/site-packages/translate/coroutines.py", line 19, in <module> from concurrent.futures import ThreadPoolExecutor ImportError: No module named concurrent.futures -
When docker run, an error occurs. "ValueError: Unable to configure handler 'watchtower': You must specify a region."
First, I use the server environment sever: django + nginx + uwsgi cloud: docker + AWS ECS logging: AWS CloudWatch log service + watchtower third party app If I run server locally with python manage.py runserver, the log is stored well in the CloudWatch log. However, if I build my project with docker and docker run --rm -it -p 8080: 80 image_name command, the following error occurs. Traceback (most recent call last): File "/usr/lib/python3.5/logging/config.py", line 558, in configure handler = self.configure_handler(handlers[name]) File "/usr/lib/python3.5/logging/config.py", line 731, in configure_handler result = factory(**kwargs) File "/usr/local/lib/python3.5/dist-packages/watchtower/__init__.py", line 78, in __init__ self.cwl_client = (boto3_session or boto3).client("logs") File "/usr/local/lib/python3.5/dist-packages/boto3/__init__.py", line 83, in client return _get_default_session().client(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/boto3/session.py", line 263, in client aws_session_token=aws_session_token, config=config) File "/usr/local/lib/python3.5/dist-packages/botocore/session.py", line 836, in create_client client_config=config, api_version=api_version) File "/usr/local/lib/python3.5/dist-packages/botocore/client.py", line 70, in create_client verify, credentials, scoped_config, client_config, endpoint_bridge) File "/usr/local/lib/python3.5/dist-packages/botocore/client.py", line 224, in _get_client_args verify, credentials, scoped_config, client_config, endpoint_bridge) File "/usr/local/lib/python3.5/dist-packages/botocore/args.py", line 45, in get_client_args endpoint_url, is_secure, scoped_config) File "/usr/local/lib/python3.5/dist-packages/botocore/args.py", line 103, in compute_client_args service_name, region_name, endpoint_url, is_secure) File "/usr/local/lib/python3.5/dist-packages/botocore/client.py", line 297, in resolve service_name, region_name) File "/usr/local/lib/python3.5/dist-packages/botocore/regions.py", line 122, in construct_endpoint partition, service_name, region_name) File "/usr/local/lib/python3.5/dist-packages/botocore/regions.py", line 135, in _endpoint_for_partition raise NoRegionError() botocore.exceptions.NoRegionError: You must specify a region. During handling … -
static files wont be found
In my base.html I am loading the static files. In some way it will not find the path, I think. I just want to use my static files by using: {% load static %} {% static 'css/bootstrap.min.css' %} {% static 'css/style.css' %} This is my map structure ToetsOmgeving _static css bootstrap.min.css style.css js _templates base.html test test_create.html test testenvironment user db.sqlite3 manage.py This is my settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_DIR = os.path.join(BASE_DIR, '_static') SECRET_KEY = 'd5-f7&tlic%)*-ol)kc8$0psb+m^l_9k4!l$l(ie$#wd=#*1is' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'test', 'user', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'testenvironment.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '_templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'testenvironment.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files … -
Running tests in django throws exception 'doesn't declare explicit app_label'
When running the tests normally ie python manage.py test everything works perfectly. However when I choose to do python manage.py test my_app I get the exception RuntimeError: Model class my_app.models.MyClass doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Not really sure how to debug that. I already have an apps.py with an appconfig inside it. And running the app normally throws no exceptions at all. Django version 1.10 -
Check if a user has voted on a Post, in the template
Here's my Post model: models class Post(models.Model): user = models.ForeignKey(User, blank=True, null=True) title = models.TextField(max_length=76) content = models.TextField(null=True, blank=True) ... class PostScore(models.Model): user = models.ForeignKey(User, blank=True, null=True) post = models.ForeignKey(Post, related_name='score') upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) And here's my template. I want to do something like this... if the user has upvoted or downvoted the Post, then hide the upvote/downvote buttons: {% if request.user in Post.has_answered %} {% else %} <img src="upvote.png" class="upvote" /> <img src="downvote.png" class="downvote" /> {% endif %} I planned to do this by adding a ManyToManyField called has_answered to my Post model, but i'm unable to do that as I get this error: post.Post.has_answered: (fields.E304) Reverse accessor for 'Post.has_answered' clashes with reverse accessor for 'Post.user'. HINT: Add or change a related_name argument to the definition for 'Post.has_answered' or 'Post.user'. post.Post.user: (fields.E304) Reverse accessor for 'Post.user' clashes with reverse accessor for 'Post.has_answered'. HINT: Add or change a related_name argument to the definition for 'Post.user' or 'Post.has_answered'. Any idea how I can fix this? I'm not too sure about the error message as I don't think I can alter my current user field. -
Django migration fails using FileField with dynamic upload path
I'm trying to use the dynamic upload path, for django FileFiled. This is my model: def use_assignment_path(instance, filename): return 'assignment/%s/%s' % (instance.name, filename) class Assignment(models.Model): admin = models.ForeignKey(Admin) name = models.CharField(max_length=50, unique=True) lang = models.CharField(max_length=5, default='c', choices=(('c', 'c'), ('java', 'java'))) pointsRecommended = models.IntegerField() file0 = models.FileField(upload_to=use_assignment_path) file1 = models.FileField(upload_to=use_assignment_path, default='', blank=True) When I try to migrate the models I get this errors: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/mb/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/mb/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mb/.local/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/mb/.local/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/mb/.local/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/mb/.local/lib/python3.5/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/mb/.local/lib/python3.5/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/home/mb/.local/lib/python3.5/site-packages/django/db/migrations/loader.py", line 203, in build_graph self.load_disk() File "/home/mb/.local/lib/python3.5/site-packages/django/db/migrations/loader.py", line 114, in load_disk migration_module = import_module("%s.%s" % (module_name, migration_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 … -
Django get ios app version automatically (app doesn't need to change any)
I am beginner in Django. I can get os version , etc if I use user-agent. https://github.com/selwin/django-user_agents For me, I need to know app version as well so that I can give different data for different app version. Is it possible to do? -
response in view instead of HttpResponse
Is there a way to only get a response to the view instead of making a HttpResponse? I'm making a xml request, and I want to use some data from teh response before doing a HttpRepsonse. I'm new to Python and Django. -
manage.py command in crontab not working
I have created a executeable script .sh which contains code to run a django managemenet command. cron.sh #!/bin/sh . /path/to/env/activate cd /path/to/project /path/to/env/bin/python manage.py some_command I can confirm this script is working by executing it directly on terminal $ /path/to/cron.sh When i do it same via crontab its not working as expected. ** What am i doing wrong ?? I can confirm there is nothing wrong with crontab, it executing the cron.sh file but path/to/env/bin/python manage.py some_command is not working as expected. cron log also showing CRON[14768]: (root) CMD /path/to/cron.sh > /dev/null 2>&1 I am using bitnami django ami (ubuntu 14.04.5 LTS) -
Django/Python http.server access 404s via proxy, works locally
I've previously had the issue that I couldn't pinpoint the culprit in my Django app, causing all requests to 404. See the previous Stackoverflow question. Since then I've tried to narrow down the issue and therefore started a new, VERY basic, Django app. All the project consists of is: $ django-admin startproject tempor I've added the test directory and imported the test function $ vi tempor/tempor/urls.py from django.conf.urls import url from django.contrib import admin from tempor.views import test urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test/$', test), ] The views.py and the test function $ vi tempor/tempor/views.py from django.http import HttpResponse def test(request): return HttpResponse("OKAY") Then I migrated the project - as suggested by Django: $ python manage.py check $ python manage.py migrate Now I run the server: $ python3 manage.py runserver 0.0.0.0:8282 Access from the server locally: $ curl localhost:8282/test/ OKAY $ curl <server-public-IP>:8282/test/ OKAY Access from an external system (via proxy) $ curl <server-public-IP>:8282/test/ <!DOCTYPE html> <html lang="en"> [...] <h1>Page not found <span>(404)</span></h1> [...] </html> In the settings.py I have: ALLOWED_HOSTS = ['*'] If I don't use '*', the external system is informed accordingly, as debugging is on: $ curl <server-public-IP>:8282/test/ [...] DisallowedHost at http://<server-public-IP>:8282/test/ [...] This also occurs, if … -
comparing value of two list python django?
i have a two list coming from my views and I am compairing them and checking the values which match on a multi select dropdown.But the logic seems to work fine but it tends to multiply the data coming in multi select. <div class="form-group"> <label class="col-sm-4 control-label text_left">University <span class="text-danger">*</span></label> <div class="col-sm-8"> <select class="form-control" value="university_all_list.id" name="universityId" id="universityName" required> <option>Select</option> {% for university_name in university_all_list %} {% for id in university %} {% if id == university_name.id %} <option value="{{ university_name.id }}" selected>{{ university_name.name }}</option> {% else %} <option value="{{ university_name.id }}">{{ university_name.name }}</option> {% endif %} {% endfor %} {% endfor %} </select> </div> </div> any solution for this that it doesnot multiply my data in dropdwon.I know i am using multiple forloop it is because of that,but what could be the solution for that. THanks -
Error after migrating Django project from MySQL to PostgreSQL
I am migrating a Django project from Mysql to Postgresql. I have been able to successfully transfer database from mysql to postgresql. But running the site gives me the follwing error: Unhandled exception in thread started by <function wrapper at 0x7f68d9b266e0> Traceback (most recent call last): File "/root/.virtualenvs/thakurani/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper _exception = sys.exc_info() AttributeError: 'NoneType' object has no attribute 'exc_info' Is this error coming because of some packages not being installed. I have installed pyscopg2, python-dev, libpq-dev. -
Django-Taggit get random tags skipping those not assigned to a Post
I want to give my users suggestions of random tags when they click on the search bar. So far my code returns what I want BUT it is also returning tags that are not assigned to any Post IE: when I delete a post or delete its tags those tags are still showing up in the suggestions. # Get the suggestions (In View) suggestions = Tag.objects.all().distinct().order_by('?')[:5] # Model class Post(models.Model): title = models.CharField(max_length=256) disclaimer = models.CharField(max_length=256, blank=True) BLOGS = 'blogs' APPLICATIONS = 'applications' GAMES = 'games' WEBSITES = 'websites' GALLERY = 'gallery' PRIMARY_CHOICES = ( (BLOGS, 'Blogs'), (APPLICATIONS, 'Applications'), (GAMES, 'Games'), (WEBSITES, 'Websites'), ) content_type = models.CharField(max_length=256, choices=PRIMARY_CHOICES, default=BLOGS) screenshot = models.CharField(max_length=256, blank=True) tags = TaggableManager() body = RichTextField() date_posted = models.DateTimeField(default=datetime.now) date_edited = models.DateTimeField(blank=True, null=True) visible = models.BooleanField(default=True) nsfw = models.BooleanField() allow_comments = models.BooleanField(default=True) files = models.ManyToManyField(File, blank=True) def __str__(self): if (self.visible == False): return '(Hidden) ' + self.title + ' in ' + self.content_type return self.title + ' in ' + self.content_type -
Django: Splitting one app into multiple: Templates, Proxy Models & ForeignKeys
To keep my project cleaner I decided (maybe wrongly) to split my one Django app into two. One app for the management of information, the other for display. And for this I thought using Django Proxy Models in the display App would be the best way. However, I've come across a problem with the ForeignKey fields within certain models and forcing those foreign keys to use a proxy-model, instead of its originating model. Here's some examples to make it clearer: App_1-model.py class Recipe(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() ... class Ingredient(models.Model): name = models.CharField(max_length=200) recipe = models.ForeignKey(Recipe) weight = models.IntegerField() App_2-model.py (Imports App_1 models) class RecipeDisplayProxy(Recipe): class Meta: proxy = True @property def total_weight(self): # routine to calculate total weight return '100g' class IngredientDisplayProxy(Ingredient): class Meta: proxy = True @property def weight_lbs(self): # routine to convert the original weight (grams) to lbs return '2lb' App_2.views.py def display_recipe(request, slug): recipe = get_object_or_404(RecipeDisplayProxy, slug=slug) return render( request, 'display_recipe/recipe.html', {'recipe': recipe} ) App_2-template.html <h2 class="display-4">{{ recipe.name }}</h2> <p>{{ recipe.total_weight }}</p> <!-- This works fine, as expected //--> <ul> {% for recipe_ingredient in recipe.ingredient_set.all %} <li>{{recipe_ingredient.ingredient}} &ndash; {{recipe_ingredient.weight_lbs}}</li> <!-- The above line doesn't return anything as the 'Ingredient' model, not the "IngredientDisplayProxy' is … -
Django: NoReverseMatch, reverse for login not found error
I am trying to send an AJAX post request to a view but I am getting an Http500 error for some reason. Here is the AJAX function: function update_coins() { $.ajax({ method: "POST", url: "/coins", data: {"coins": transaction}, success: function(data) { console.log('yay') $( ".status" ).contents()[0].textContent = "Balance: " + data.coins } }) }; and I copy+pasted the necessary Django CSRF code above it. The error I am getting is: django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. "POST /coins HTTP/1.1" 500 59 I'm guessing that this has something to do with my urls.py. Here is my root app's urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^home$', views.home, name='home'), url(r'^coins$', views.update_coins, name='coins'), url(r'^shop', include('shop.urls', namespace='shop')), url(r'^users/', include('users.urls', namespace='users')), url(r'^oauth/', include('social_django.urls', namespace='social')), ] Here is my shop app's urls.py: urlpatterns = [ url(r'^', views.shop, name='shop'), ] and finally my users app's urls.py urlpatterns = [ url(r'^login/$', views.login_view, name='login'), url(r'^logout/$', views.logout_view, name='logout'), url(r'^change-password/$', views.change_password, name='change_password'), url(r'^register/$', views.register, name='register'), ] Thank you! -
Django slow query since unable to use related set
I am using version 1.8 class ProductProduct(models.Model): product_tmpl = models.ForeignKey(ProductTemplateModel) default_code = models.CharField() name_template = models.CharField() ... class PurchaseOrder(models.Model): # fields... class PurchaseOrderLine(models.Model): id = models.IntegerField() product_id = models.ForeignKey(ProductProduct) order_id = models.ForeignKey(PurchaseOrder) I only need to list the PurchaseOrder records which default_code (in ProductProduct model) is null. I cannot filter using "purchaseorderline_set.product_id_set.default_code=None" since purchaseorderline_set is a query set and it does not have an attribute product_id_set as indicated here. So I tried using this: orders_recs = PurchaseOrder.objects.all().order_by('-id') orders_recs = PurchaseOrder.objects.filter(purchaseorderline_set.product_id_set.default_code=None).order_by('-id') orders = [] for order_rec in orders_recs: line = order_rec.purchaseorderline_set.all() if line and line[0].product_id.default_code == None: orders.append(order_rec) But it's taking over 3 secs. I consider this A LOT taking in consideration that I am only one working in my DEV env (machine is NOT slow) and DB is really small so far, since there are only 269 PurchaseOrder recs, 396 PurchaseOrderLine recs and 726 ProductProduct recs. I suppose there is an efficient way that I am not seeing. -
Unable to receive message from websocket in django-channels
Im using django-channels with django-tenant-schemas, I'm having difficult time in sending data. Group('dynamic-group').send({"text": json.dumps(data)}) Its always on pending Not receiving any data -
Redirect to the same view while changing one parameter
I have an ajax call that sends a country label to my view function below: views ... posts = Post.objects.all() if request.method == 'POST': country = request.POST.get('country') print('COUNTRY:', country) #successfully prints posts = Post.objects.filter(country=country) context = { ... 'posts': posts, } return render(request, 'boxes.html', context) I successfully get the ajax data but what do I do after this in order to redirect to the same view with the new posts value? -
Executing bootstrap modal on same view in Django with an argument
I want to display modal on the same view, from where i clicking the button. This is my view def save_to_db(request): try: db.save() # saving a data in database results = '[Success] Records Saved' except IntegrityError: results = '[Duplicate Error] Records Exist' context = { 'results' : results # string to display in modal body } template = loader.get_template('modal.html') return HttpResponse(template.render(context,request)) My modal.html is coded on page load so whenever the page is loaded it is displayed. How can i display this modal on the same view, which is calling it? As i am doing database saving so i have to do this from views and after saving in database i want to display success or error info.