Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dose Django hava a function like `abort` in Flask? I want to break a request in deal with request params
I want to dealwith request parameters in Django more elegant and here is my code: With that I can use in my view function like this: def testparam(request): name = request_get(request, 'name', required=True) age = request_get(request, 'age', ptype=int, required=True) print('name: ', name) print('age: ', age) return HttpResponse('test param run') Then I ran my Django applicaiton and typed url(http://127.0.0.1:8000/test/param) in chrome but I still got the response with "test param run". I want my django to make a response when request_get function called just like abort function in flask framework. Someone can help me? -
Using Celery with a cookiecutter-django project
I'm currently building a small django project and I decided to use cookiecutter-django for a base as everything I need was included. When setting up the project I asked cookiecutter-django to include the settings for Celery and I can find everything in the project, so far so good. However I do have some issues with getting Celery to run as it should. When I start a task from from an app nothing happens. The docker containers are all started properly. Django and Postgres work, Redis is up and I was able to bash into the container and query it. From the console output I see that the celeryworker container is up and running. I also see that my tasks are being recognized by Celery: celeryworker_1 | [tasks] celeryworker_1 | . metagrabber.taskapp.celery.debug_task celeryworker_1 | . scan_and_extract_meta celeryworker_1 | . start_job After puzzling a lot about this I decided to create a new Docker container for Flower to see what's happening under the hood. Interestingly enough I can see that there is a worker and its name is correct (I compared the worker ID in the Celery container). However if I start a task from one of my views like this: celery_task_id … -
Djano /w gunicorn bottlencking with tiny cpu and memory usage
I have a django/gunicorn/nginx app on D.O. which starts throwing this error once I get up to 50 req/s. [error] 1608#1608: *584100 connect() to unix:/my/app/gunicorn.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: 162.158.222.46, server: hbs.hubro.education, request: "GET /notification/count/ HTTP/1.1", upstream: "http://unix:/my/app/gunicorn.sock:/notification/count/", host: "mydomain.com" The cpu usage is really low, in the 10% area, same with memory. I've tried with gunicorn workers equaling the number of cores, twice the cores, and four times the cores, but it seems the bottleneck is somewhere else. I would be grateful for suggestions on figuring out where the bottleneck is, and if there are any recommended monitoring tools that can give me more data on the issue than the D.O dashboard, like response times, open file count, workers utilized and whatnot. -
Dynamic Model Form Fields
I have a model formset. One of the fields in the base model is a charfield. I need this field to carry different choices depending on the form. i.e. Within the formset, some forms will have choices a,b & c and others will have choice e,f and g. Despite reading Django documentation and several Q&A's in stack overflow, I'm still at a loss. The Django documentation says: Note that choices can be any iterable object – not necessarily a list or tuple. This lets you construct choices dynamically. However, it does not give an example how to do this. Would be grateful if someone could give me an example. My model: class Item(models.Model): budgetcatagory=models.ForeignKey(BudgetCatagory, on_delete=models.CASCADE) name=models.CharField(max_length=50) enName=models.CharField(max_length=30, default ="") detail=models.CharField(max_length=30) layout=models.CharField(max_length=30, default="normal") unit=models.CharField(max_length=30) unit_description=models.CharField(max_length=30, default="") unit_price=models.IntegerField(default=0) QTY=models.IntegerField(default=0) param1=models.CharField(max_length=30, blank=True) param2=models.CharField(max_length=30, blank=True) param3=models.CharField(max_length=30, blank=True) param4=models.IntegerField(default=0) parent=models.CharField(max_length=50, default = "0") cost_ave=models.IntegerField(default=0, blank=True) cost_min=models.IntegerField(default=0, blank=True) cost_max=models.IntegerField(default=0, blank=True) total_cost=models.IntegerField(default=0) objects=ItemManager() def __str__(self): return self.name Instances get constructed via the following code in an object manager: def normalCreate(self, cat, parent, name, description, unit, U, enName, Param1, Param2, Layout, min_val, max_val, ave_val): #import pdb #pdb.set_trace() if parent=="פיתוח": q=House.objects.get(user_id=U.id).plot_size else: q=House.objects.get(user_id=U.id).area I=self.create(budgetcatagory_id=cat.id, name=name, unit=unit, detail='Low', unit_description=description , parent=parent, QTY=q, unit_price=ave_val, total_cost=ave_val*q, enName=enName, cost_min=min_val, cost_max=max_val, cost_ave=ave_val ) I.save() … -
template not exist, everything is correct yet not working
I know it has been asked, but, this is different, please have a look below: I've just create a very simple test project, the folder structure is as such: Ignore the red marks, it's because, it was said to not detect meta programming issues. Just for simplicity sake, I've made the view to be called in the homepage itself, the main project urls.py has the urls: """testproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, re_path from test1.views import test1_detail urlpatterns = [ path('admin/', admin.site.urls), re_path('^$', test1_detail) ] The tag_detail1 views file is just this: from django.shortcuts import render from test1.models import model_test1 as Model from django.shortcuts import render def test1_detail(request): tag = Model.objects.get(name__iexact='birlaman') return render(request, 'test1/test.html', {'tag':tag}) The model database is just a … -
AlamoFire POST will get 'GET not allowed' error form DRF server
Used techs Django 2 with Django Rest Framework (Drf) JWT for authentication iOS/Swift4/Alamofire here the issue. django will recieve Alamofire's POST request as GET request. iOS/swift4 code. static func getToken (){ let username = "root" let password = "DAMnShEIsSoHo1!t" let parameters: [String: Any] = [ "username" : username, "password" : password, ] let url = ApiController.baseServerUrl + "api-token-auth" print("URL :: \(url)") Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default) .responseJSON { response in print("RESPONSE :: \(response)") } } log from iOS RESPONSE :: SUCCESS: { detail = "Method \"GET\" not allowed."; } log from django server my.ip.address - - [04/Mar/2018:07:55:32 +0000] "GET /api-token-auth/ HTTP/1.1" 405 40 "-" "Foodle/0.0.1 (com.domain.Appname; build:2; iOS 11.2.0) Alamofire/4.6.0" what shall i do from here? ps. it works fine on PostMan, DRF web console and CURL -
How to show PasswordResetForm errors in Django messages
I have the following view for my page to reset your password: from django.contrib.auth.forms import PasswordChangeForm def password_change(request): if request.method == 'POST': password_form = PasswordChangeForm(data=request.POST, user=request.user) if password_form.is_valid(): password_form.save() update_session_auth_hash(request, password_form.user) messages.add_message(request, messages.SUCCESS, "Password reset.") return redirect(reverse('elections:home')) else: messages.add_message(request, messages.ERROR, "Error with password reset.") return redirect('/password/new/') else: password_form = PasswordChangeForm(user=request.user) return render(request, 'registration/password_change.html', { 'form': password_form }) Some of my users are reporting that they are unable to change their password, but it is working for me. As I can't ask them what their password is for obvious reasons, I need a more informative error feedback to the user. It is my understanding that PasswordChangeForm generates errors that I can access. Is this true, and if so how do I access these errors in the view to add them to the Django message? If not, how do I create my own form that will return these errors? -
Django CharField not defined
from django.db import models class Pet(models.Model): SEX_CHOICES = [('M','Male'), ('F', 'Female')] name = CharField(max_length=100) submitter = CharField(max_length=100) species = CharField(max_length=30) breed = CharField(max_length=30, blank=True) description = models.TextField() sex = models.CharField(choices=SEX_CHOICES, max_length=1, blank=True) submission_date = models.DateTimeField() age = models.IntegerField(null=True) vaccinations = models.ManyToManyField('Vaccine', blank=True) class Vaccine(models.Model): name = models.CharField(max_length=50) With this code I am getting command line error when running "python manage.py makemigrations". name "CharField" is not defined. How to fix it. -
Django ORM - N rows per column. Convert SQL query to ORM query
Please convert this query - select l.id, l.product_category_id from clientapi_product l join clientapi_product r on l.product_category_id = r.product_category_id and r.id >= l.id where r.product_category_id in (1,3) group by l.id having count(*) < 5; As you can see, this query is a solution to "N rows per column value" problem, where, in this case, n = 5. So, in case you have another solution to this problem in Django ORM, that solution is also welcome. -
Django rest framework many=True serializer return unexpected result on overriding to_representation
class MyModelSerializer(serializers.Serializer): def to_representation(self, data): print(data) print(self.instance) # here data will be an object from the queryset. so this method(to_representation) will # be called as many times as number of objects in queryset (default = 10 objects) # we can get whole queryset from `self.instance` variable data_list = [{'a': 1}, {'b': 2}] # dummy data_list to check respone structure return data_list queryset = self.model.objects.all() serializer = MyModelSerializer(queryset, many=True) return Response(serializer.data) Now the problem is, serializer.data will have a a list of list and each sub list will have same data returned by to_representation method. i.e [ [{'a': 1}, {'b': 2}], [{'a': 1}, {'b': 2}], [{'a': 1}, {'b': 2}], [{'a': 1}, {'b': 2}], ... # This will be repeated number of times queryset has objects ] What is wrong with this approach. -
How to create pre_populated_field in admin django like slug
i want create a custum auto populated field in admin django like slug but calculate another thing , not slugify. how do this ? -
Django - attributes and redefined fields with a ModelForm?
I have been learning about how forms, and now ModelForms, work. In a video by Max Goodridge, he redefines a field for one of his ModelFields in his ModelForm class. That is, he manually adds a field to his ModelForm class that could have been auto-generated by the ModelForm framework. From what I have read and understood thus far, that may be something to avoid. Though, that is not where my question lies. I am wondering how redefining fields within a ModelForm class works. In the Django Docs, it is stated (with an example) that a ModelForm instance will have a form field for every model field specified. What happens then, when a form field is explicitly defined in a ModelForm instance? Are two fields generated or does ModelForm recognise that a field is already defined, thus not generating another one? Furthermore, what exactly does adding an attribute to a ModelForm instance in the views do? For example, I have seen this: form = ExampleForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user # herein lies my confusion What exactly is happening here? I have seen people do this and adding a timestamp as well, but I fail to understand … -
When conda install django, PermissionError(13, 'Permission denied')
When I run conda install django, I get the following error: Solving environment: done ==> WARNING: A newer version of conda exists. <== current version: 4.4.10 latest version: 4.4.11 Please update conda by running $ conda update -n base conda Package Plan environment location: /opt/anaconda/anaconda3 added / updated specs: - django The following NEW packages will be INSTALLED: django: 2.0.2-py36hd476221_0 Proceed ([y]/n)? y Preparing transaction: done Verifying transaction: done Executing transaction: failed ERROR conda.core.link:_execute(481): An error occurred while installing package 'defaults::django-2.0.2-py36hd476221_0'. PermissionError(13, 'Permission denied') Attempting to roll back. Rolling back transaction: done PermissionError(13, 'Permission denied') What should I do? -
Django, Redirect user to different page by user's type
I want to redirect user to different page by user's type when they login. I'm using django-allauth for login system and I created a profile table for user that has a OnetoOne field with the user table, like this.... #models.py class Profile(models.Model): TYPE_CHOICES = ( ('sup', 'supplier'), ('dis', 'distributor'), ) type = models.CharField(max_length=3, choices=TYPE_CHOICES, unique=True, null=True, blank=True, default=None) user = models.OneToOneField(User, on_delete=models.CASCADE) nationality = CountryField() company = models.CharField(max_length=50, unique=True, null=True, blank=True, default=None) phone = models.CharField(max_length=50, unique=True, null=True, blank=True, default=None) skype = models.CharField(max_length=50, unique=True, null=True, blank=True, default=None) address = models.CharField(max_length=50, unique=True, null=True, blank=True, default=None) After their login, they will access a view called "redirect". (exampale.com/app/rediect) for this view, I'm using this #views.py @login_required def redirect(request): if request.user.profile.filter(type='sup'): return redirect('/app/a') elif request.user.profile.filter(type='dis'): return redirect('app/b') However, when I access this page. There is a error File "/opt/project/app/views.py", line 27, in redirect if request.user.profile.filter(type='adv'): AttributeError: 'Profile' object has no attribute 'filter' Does anyone know what is the problem? -
How can I add a parameter when consuming a post service without this field being in the form?
I am sending by parameter upload_preset, and this corresponds to the name of the text field, but from javascript I would like to send another parameter called folder with the value, myvalue. how can I do it without needing to add another text field called folder? <form action="" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;"> <fieldset> <legend>Upload example</legend> <p> <label for="upload_preset">Unsigned upload Preset: <input type="text" name="upload_preset" value="xx">(set it <a href="https://cloudinary.com/console/settings/upload#upload_presets">here</a>)</label> </p> <p> <label >Select your photo: <input type="file" name="file"></label> </p> <p> <input type="submit" value="Submit" /> </p> <img id="uploaded"> <div id="results"></div> </fieldset> </form> window.AJAXSubmit = function (formElement) { if (!formElement.action) { return; } var xhr = new XMLHttpRequest(); xhr.onload = ajaxSuccess; xhr.open("post", "https://api.cloudinary.com/v1_1/xxx/image/upload"); xhr.send(new FormData(formElement)); } -
Django ModuleNotFoundError when adding app
I'm using Visual Studio with Python tools to develop my Django project. I've create an app through the IDE. However after adding the app into the INSTALLED_APPS in my settings.py, it is always giving me ModuleNotFound Error This is the directory structure. This is how I've added the app INSTALLED_APPS = [ # Add your apps here to enable them 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'kleis', ] Stacktrace Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000228FCA30A60> Traceback (most recent call last): File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\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 'kleis' -
Django template: force choices on field and print display value with get_FOO_display()
I want a model with 5 choices, but I cannot enforce them and display the display value in template. I am using CharField(choice=..) instead of ChoiceField or TypeChoiceField as in the docs. I tried the solutions here but they don't work for me (see below). model.py: class Language(models.Model): language = models.CharField(max_length=20,blank=False) ILR_scale = ( (5, 'Native'), (4, 'Full professional proficiency'), (3, 'Professional working proficiency'), (2, 'Limited professional proficiency'), (1, 'Elementary professional proficiency') ) level = models.CharField(help_text='Choice between 1 and 5', default=5, max_length=25, choices=ILR_scale) def level_verbose(self): return dict(Language.ILR_scale)[self.level] class Meta: ordering = ['level','id'] def __unicode__(self): return ''.join([self.language, '-', self.level]) view.py .. def index(request): language = Language.objects.all() .. mytemplate.html <div class="subheading strong-underlined mb-3 my-3"> Languages </div> {% regroup language|dictsortreversed:"level" by level as level_list %} <ul> {% for lan_list in level_list %} <li> {% for lan in lan_list.list %} <strong>{{ lan.language }}</strong>: {{ lan.level_verbose }}{%if not forloop.last%},{%endif%} {% endfor %} </li> {% endfor %} </ul> From shell: python3 manage.py shell from resume.models import Language l1=Language.objects.create(language='English',level=4) l1.save() l1.get_level_display() #This is good Out[20]: 'Full professional proficiency' As soon as I create a Language instance from shell I cannot load the site. It fails at line 0 of the template with Exception Type: KeyError, Exception Value: … -
uWSGI + Django + Nginx - Runtime Error
First post on Stackoverflow + help is definitely needed: I'm trying to set up a Ubuntu 16.04 server to host my Django app but I'm running into a weird error with the uWSGI; whenever I run: uwsgi --socket test.sock --module api.wsgi:app --chmod-socket=66 I get this: Python version: 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0x8025d0 uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 72920 bytes (71 KB) for 1 cores *** Operational MODE: single process *** Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 890, in _find_spec AttributeError: 'ConfigurationImporter' object has no attribute 'find_spec' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./api/wsgi.py", line 14, in <module> from configurations.wsgi import get_wsgi_application File "/usr/local/lib/python3.5/dist-packages/configurations/wsgi.py", line 14, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File … -
__init__() missing 3 required positional arguments: - Django 2.0
This error happens when I try to access an instance of my model into admin, this is my models.py: from django.db import models class Repo(models.Model): name = models.CharField(primary_key=True, max_length=150) creation_datetime = models.DateTimeField() update_datetime = models.DateTimeField() def __init__(self, name, creation, update, *args, **kwargs): super(Repo, self).__init__(*args, **kwargs) self.name = name self.creation_datetime = creation self.update_datetime = update def __str__(self): return self.name class Stats(models.Model): name = models.CharField(primary_key=True, max_length=30) value = models.TextField() def __str__(self): return self.name This is my admin.py: from django.contrib import admin from webapp.models import Repo admin.site.register(Repo) This is the traceback: Internal Server Error: /admin/webapp/repo/add/ Traceback (most recent call last): File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/contrib/admin/options.py", line 551, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/contrib/admin/sites.py", line 224, in inner return view(request, *args, **kwargs) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/contrib/admin/options.py", line 1508, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/utils/decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File … -
Why does Django raised IntegrityError :null value in column "user_id" violates not-null constraint when a form is committed?
I have a UserSession model that creates a session that uses the IPaddress, and city data to populate the model using Geip2. I set up a form that takes the info that I want the user to enter but get: **django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint** when I submit the form. The object gets created but the information that the form takes doesn't save to the object. views: class NewLocationCreateForm(CreateView): model = UserSession success_url = reverse_lazy('post:index') form_class = NewLocationCreateForm def form_valid(self, form): if form.is_valid(): roote = Post.objects.filter(owner =self.request.user) instance = form.save(commit=False) instance.owner = self.request.user user_logged_in.send(self.request.user, request=self.request) return super(NewLocationCreateForm, self).form_valid(form) def get_form_kwargs(self): kwargs = super(NewLocationCreateForm, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs The problem seems to arrive at at is: if form.is_valid(): return super(NewLocationCreateForm, self).form_valid(form) The user session call of the Geoip2 seems to work but it doesn't save the form forms.py from .models import UserSession from post.models import Post from django import forms class NewLocationCreateForm(forms.ModelForm): class Meta: model = UserSession fields = [ 'g_post', 'coordinate', 'place_name' ] def __init__(self,user=None, *args, **kwargs): super(NewLocationCreateForm, self).__init__(*args, **kwargs) self.fields['g_post'].queryset = Post.objects.filter(owner=user) models.py: from django.conf import settings from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User from django.db.models.signals import pre_save … -
Accessing a field on a Django model that is linked to a different model via the User model
I have the following models: class Reputation(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) score = models.IntegerField(default=0) .... class Article(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL) .... I am trying to access the "score" field on the Reputation model from an Article object. I tried the following on an Article object (article_object), but it does not work: article_object.created_by.reputation_set.score Is there any way I can access "score" from an Article object? Thank you. -
Connecting React Frontend to Django Backend
I have been looking at plenty of tutorials namely [this] (https://blog.cloudboost.io/react-redux-webpack-3-django-nov-2017-53a09d09cf75) and a blog [posted] (http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/) 4 months ago. Do these still apply with the update to Django? If not, can someone send me in the right direction? -
Django: request to database or substitution value
Im study the Django. Essence: I check the user lang and replace text depending on the language but does not work. def check_lang(chat_id): # Проверка языка global language con = lite.connect('db.sqlite3') cur = con.cursor() sql = "SELECT Lang FROM Userprofile WHERE Id={} ".format(chat_id) cur.execute(sql) lang_user = cur.fetchone() if lang_user is None: language = "request_base.english" elif lang_user[0] == 'English': language = "request_base.english" else: language = "request_base.russian" def settinngs(chat_id, message): check_lang(chat_id) global language request_base = Loclizationmain.objects.get(keys__exact='change_city') change_city_text = language request_base = Loclizationmain.objects.get(keys__exact='button_subs') button_subs_text = language The model 'Loclizationmain' contains three field: keys, russian, english Сan i create in Queryset this request? SELECT {} FROM aut_loclizationmain WHERE keys={} " .format(language, chat_id) -
show price and rating in facet search
I want to show rating and price range in facet search however the rating is not displayed and price range is displayed but is disabled. What else should i have to do to show them in facet search? This is the source code of django-oscar. Here is the configuration FURNITURE_SEARCH_FACETS = { 'fields': OrderedDict([ ('product_class', {'name': _('Type'), 'field': 'product_class'}), ('rating', {'name': _('Rating'), 'field': 'rating'}), ]), 'queries': OrderedDict([ ('price_range', { 'name': _('Price range'), 'field': 'price', 'queries': [ # This is a list of (name, query) tuples where the name will # be displayed on the front-end. (_('0 to 20000'), u'[0 TO 20000]'), (_('20000 to 40000'), u'[20000 TO 40000]'), (_('40000 to 60000'), u'[40000 TO 60000]'), (_('60000+'), u'[60000 TO *]'), ] }), ]), } class ProductIndex(indexes.SearchIndex, indexes.Indexable): # Search text text = indexes.CharField( document=True, use_template=True, template_name='search/indexes/product/item_text.txt') name = indexes.EdgeNgramField(model_attr='name', null=True) name_exact = indexes.CharField(model_attr='name', null=True, indexed=False) # Fields for faceting product_class = indexes.CharField(null=True, faceted=True) category = indexes.MultiValueField(null=True, faceted=True) price = indexes.FloatField(null=True, faceted=True) num_in_stock = indexes.IntegerField(null=True, faceted=True) rating = indexes.IntegerField(null=True, faceted=True) # Spelling suggestions suggestions = indexes.FacetCharField() date_created = indexes.DateTimeField(model_attr='created_at') date_updated = indexes.DateTimeField(model_attr='updated_at') _strategy = None def get_model(self): return get_model('catalogue', 'Product') def index_queryset(self, using=None): # Only index browsable products (not each individual child product) return … -
Django Sending Nav Pill Selection
I have two pills here: I just want to be able to click on them and have a variable be sent to my 'views' code to tell me which one is selected. Here is the html: <div class="col-md-2" id = "charts_tables"> <ul class="nav nav-pills nav-stacked" id = charts_tables> <li {% if type_display == 'charts' %} class="active"{% endif %}><a href="" name = "radio-option" class="text-primary" {{type_display}} == 'charts'><i class="fa fa-fw fa-bolt"></i> Charts</a></li> <li {% if type_display == 'tables' %} class="active"{% endif %}><a href="" name = "radio-option" class="text-primary" {{type_display}} == 'tables'><i class="fa fa-fw fa-calendar"></i> Tables</a></li> </ul> Ideally, when pushed I'd like to set the "type_display" variable to the name of the selected pill and pass that variable to my view file. I tried to make a similar post, but the only answer I receieved was to use radio buttons. For this project it has to be nav pills. Here's the top of my view: def analysis_view(request, action=None): print(request.GET.get("radio-option")) I've been trying to find documentation for the past two days and nothing. I don't even see a nav-pills widget type in any docs. Any help would be greatly appreciated.