Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble with supervisor reread?
I use NGINX+DJANGO+GUNICORN+SUPERVISOR virtualenv with python3.6. I created mysite.conf at /etc/supervisor/conf.d [program:mysite] command = /home/split/mysite/gunicorn_start.bash ; Command to start app user = split ; User to run as stdout_logfile = /home/split/logs/gunicorn_supervisor.log ; Where to write log messages redirect_stderr = true ; Save stderr in the same log environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 ; Set UTF-8 as default encoding After that I tried to reread supervisor sudo supervisorctl reread And got error: <class 'socket.error'>, [Errno 2] No such file or directory: file: /usr/lib/python2.7/socket.py line: 228 help please.e -
django options mounted via ajax break with browser back button (history api)
I have a form with 2 selects where the second one is filtered based on the first. The second select options are filtered and mounted via an ajax request. However although that works fine and the form submits correctly etc.. when I go back in the browser (eg as part of a signup flow), the form is broken and the second option doesn't appear with the selected choice as the first select does. The second select does pull down the possible choices when the form is bound with data, but presumably the form isn't bound when going back with the browser. (I'm not clear how django interacts with the browser history api to populate previously submitted fields). How should the form be amended to work correctly when going back in the browser? (note options are pulled from an external api not the db): forms/py class CurrentSupplierForm(forms.Form): current_supplier = forms.ChoiceField() product_choices = [('', '---- Please select your current supplier first ----')] current_product = forms.ChoiceField(choices=product_choices) def __init__(self, session, *args, **kwargs): super().__init__(*args, **kwargs) # we get supplier choices from api dynamically self.session = session region = session.get('region') product_choices = [('', '---- Please select your current supplier first ----')] self.current_supplier_choices = get_supplier_choices(region) self.fields['current_supplier'].choices = … -
Django test(django.test.client) put call, with many headers don't work
Work, it Works very well. client = Client() response = client.put('/api/v1/person/address/',{}, HTTP_API_KEY=self.model_login_director.token) Dont work(with put does not work, but GET and POST work...). client = Client() response = client.put('/api/v1/person/address/',{}, REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token) Message error Traceback (most recent call last): File "/home/wborba/project/willcode/sofia/api/test/testsControllerPersonAddress.py", line 577, in test_person_address_update_address_id_missing HTTP_API_KEY=self.model_login_director.token) File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 548, in put response = super().put(path, data=data, content_type=content_type, secure=secure, **extra) File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 366, in put secure=secure, **extra) File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 404, in generic return self.request(**r) File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 485, in request raise exc_value File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 89, in dispatch return handler(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/lib/python3.5/contextlib.py", line 30, in inner return func(*args, **kwds) File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 62, in _wrapper return bound_func(*args, **kwargs) File "/usr/lib/python3.5/contextlib.py", line 30, in inner return func(*args, **kwds) File "/home/wborba/project/willcode/sofia/api/Business/Auth.py", line 145, in wrap return function(request, model_login, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 58, in bound_func return func.get(self, type(self))(*args2, **kwargs2) TypeError: put() takes 2 positional arguments but 3 were given ---------------------------------------------------------------------- -
Django Queryset - Sort alphabetical then move specific entries to top
I'm trying to put a User ModelChoice select on a form that is sorted alphabetically, but 2 specific users (members of a particular permissions group) are at the top. Given that I'm using Django 1.11 I thought I'd try the new .union ORM function: group_members = User.objects.filter(groups__name="AddEditCalibrations") everyone_else = User.objects.exclude(username__in="group_members").sort("first_name", "last_name") total_qs = group_members.union(everyone_else) Which just raises the error: ('22018', "[22018] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting the nvarchar value 'testusername' to data type int. (245) (SQLExecDirectW)") And the even simpler: total_qs = User.objects.sort(groups__name="AddEditCalibrations", "first_name", "last_name") Which raises error: SyntaxError: positional argument follows keyword argument -
keyup event is not listened in form inside django template
I am using javascript and django for the first time. In my form, I need to show basic amount from the calculation of two field i.e quantity and rate. For that I did the following {% block content %} <div class="right_col" role="main"> <h1 class="text-center"> Purchase Order</h1> <div class="space"></div> <!-- {%include 'includes/form.html'%} --> {%include 'dashboard/purchase_order/purchase_order_form.html'%} </div> {% endblock content %} {% block javascripts %} {{ block.super }} <script> $(document).ready(function() { console.log('dom is ready'); $('#form-change').keyup(function() { console.log('form') var quantity = document.getElementById('id_quantity').value; var rate = document.getElementById('id_rate').value; if (quantity && rate) { document.getElementById('id_basic_amount').value = parseInt(quantity) * parseInt(rate); } }) }) </script> {% endblock javascripts %} <form id="demo-form2 form-change" class="form-horizontal form-label-left" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <div class="col-md-6 col-sm-6 col-xs-12"> <input type="number" name="quantity" value="0" min="0" class="form-control col-md-7 col-xs-12" required="" id="id_quantity"> </div> </div> <div class="form-group"> <div class="col-md-6 col-sm-6 col-xs-12"> <input type="number" name="rate" value="0.0" step="0.01" class="form-control col-md-7 col-xs-12" required="" id="id_rate"> </div> </div> <div class="form-group"> <div class="col-md-6 col-sm-6 col-xs-12"> <input type="number" name="basic_amount" value="0.0" step="0.01" class="form-control col-md-7 col-xs-12" required="" id="id_basic_amount"> </div> </div> </form> but the keyup event is not listened. The line console.log('dom is ready') is shown in the console but the line console.log('form') is not consoled in the console. I tried separate javascript in jsbin … -
How to Hide default help_text fom date fields in django admin
I have a django model that has one date field. class Employee(AbstractUser): dob = models.DateField(verbose_name="Date of Birth", null=True) when i register this model in admin site and display this field on the form during update, I see this default text for date fields. How can i remove this default help_text Note: You are 5.5 hours ahead of server time I tried to override the help_text for date feild but it didn't work. dob = models.DateField(verbose_name="Date of Birth", null=True, help_text='') -
Django + NGINX + uwsgi
I was following the documentation in this link :- https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html but I need something practical for production environment Please advise me where to go and read thanks ! -
Django send all sql queries in view into diffrent database
I would like to know the least problematic way to redirect all queries to views in another database. I have the Class Based view and I can in use in all queries: using('second'), but I think this way is not very clean, especially if all queries are not sent directly in the view. May it is necessary to change the type of view to Function Based view and write custom decorator? -
ipdb Step loop doesn't complete
I am debugging a Django request, working with ipdb step by step through to find the source of the problem. At a certain point, the stepping process, using s for step seems to loop endlessly. If I press c for continue, the program does not get caught at the same point, but continues to an error elsewhere (as expected). As well as being behaviour I did not expect, it also means I cannot find the source of the problem. Here is my console log which loops endlessly: ipdb> s False > /Users/technical/.virtualenvs/wagtest-QzaRrIlX/lib/python3.6/site-packages/django/apps/registry.py(236)<genexpr>() 235 self.check_apps_ready() --> 236 return any(ac.name == app_name for ac in self.app_configs.values()) 237 ipdb> s --Return-- False > /Users/technical/.virtualenvs/wagtest-QzaRrIlX/lib/python3.6/site-packages/django/apps/registry.py(236)<genexpr>() 235 self.check_apps_ready() --> 236 return any(ac.name == app_name for ac in self.app_configs.values()) 237 ipdb> s --Call-- False > /Users/technical/.virtualenvs/wagtest-QzaRrIlX/lib/python3.6/site-packages/django/apps/registry.py(236)<genexpr>() 235 self.check_apps_ready() --> 236 return any(ac.name == app_name for ac in self.app_configs.values()) 237 ipdb> s False > /Users/technical/.virtualenvs/wagtest-QzaRrIlX/lib/python3.6/site-packages/django/apps/registry.py(236)<genexpr>() 235 self.check_apps_ready() --> 236 return any(ac.name == app_name for ac in self.app_configs.values()) 237 ipdb> locals() {'.0': <odict_iterator object at 0x10fc30308>, 'app_name': 'django.contrib.sites', 'ac': <WagtailImagesAppConfig: wagtailimages>, '__return__': False} Any ideas? Thank you. -
How to configure Django such that emails are sent by both smtp, and to a log file?
I'm frequently plagued by the complaints that email from a django application running on its own Ubuntu LTS 16.04 server, is not being received. Typically these are the password change request emails, so they're part of the standard Django Auth module as I understand it. Django's sendtestemail appears to work reliably, and many of the expected emails are actually sent and received (from what we can discern). The smtp setup is such that EMAIL_HOST is set to an smtp server on the same network that supports anonymous message relay (from servers on the same network only), and the EMAIL_BACKEND is the typical django.core.mail.backends.smtp.EmailBackend. Using the console backend for testing shows that emails are triggered as we would expect on these various events. So, what I want to be able to do, is to have both email sent out via the smtp relay as expected, but also be added to a log file, and for this to happen for all emails generated by all the email events in the Django app. Is this possible using django configuration? If not, can you recommend a method by which I can both send and log the emails? Bonus query - can the solution allows … -
Datatable is not showing after using django pagination
I am having problem with pagination in django. After using pagination,not even able to show table in the template.Please find below views.py and template views.py def jobdetail(request,projectname_id,jobinformation_id): project_name=Projectname.objects.order_by('name') jobs=Projectname.objects.get(pk=projectname_id) jobdetail=Jenkinsjobsname.objects.get(pk=jobinformation_id) test=jobdetail.jenkinsjobsinformation_set.all() page = request.GET.get('page',1) paginator=Paginator('test',10)# show 10 results per page try: results = paginator.page(page) except PageNotAnInteger: results = paginator.page(1) except EmptyPage: results=paginator.page(paginator.num_pages) context = {'jobs': jobs,'categories':project_name,'results':results} return render(request,'buildstatus/job_detail.html', context) job_detail.html {% for result in results %} <tbody> <tr> <td>{{ result.build }}</td> <td>{{ result.date }}</td> <td>{{ result.Status }}</td> <td>{{ result.Sanity }}</td> <td>{{ result.Smoke }}</td> <td>{{ result.System }}</td> </tr> </tbody> {% endfor %} -
How to repreent a complex nested Structure in python/django/django rest using enums
I have a cost table that I need to represent in a django view, something like shown below. The costs returned from the db (group-by & sums)(queryset) for one device are like this: What would be the best way/pythonic way to build the data structure to represent the first image from the queryset such that I don't loop over it multiple times. I have tried a few different ways. The structure is returned using DJANGO REST and needs to support pagination. from enum import Enum class TaskTypes(Enum): I = 'I' O = 'O' T = 'T' class CostTypes(Enum): Maintenance = 'Maintenance' Repair = 'Repair' Service = 'Service' def get_cost_type(cost_type,record): cycle_costs = dict() cycle_costs['cost'] = record[cost_type] cycle_costs['year'] = record['year'] return cycle_costs def calculate_costtype_by_year(task_type, resultset): cost_types = [] for cost_type in CostTypes: print "Calculating for type", cost_type.value type_costs_structures = dict() type_costs_structures['cost_type'] = cost_type.value for record in resultset: cost_array = type_costs_structures.get('cost_by_years',[]) year_costs = get_cost_type(cost_type.value, record) cost_array.append(year_costs) type_costs_structures['cost_by_years'] = cost_array cost_types.append(type_costs_structures) return cost_types def calculate_task_costs(task_type, resultset): type_costs = [] for task_type in TaskTypes: type_cost_dict = dict() type_cost_dict['task_type'] = task_type cost_types = calculate_task_costs_by_years(task_type, resultset) type_cost_dict['task_costs'] = cost_types type_costs.append(type_cost_dict) return type_costs This works well, but not efficient or pythonic as looping multiple times through the queryset … -
How to get field value in the Serializer
I want to get id value passing in the serializer that is id = serializers.IntegerField(label='ID') in the function to get the profile object def profile_info(self, obj) But it giving the error id is IntegerField please pass the int or string Can Anybody tell me how to get values passed in id field thanks. Down below is my serializer code class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField(label='ID') # print ('dadddaaa ',serializers.data) profile = serializers.SerializerMethodField('profile_info') username = serializers.CharField() first_name = serializers.CharField() last_name = serializers.CharField() # Nazir = serializers.CharField() # profile = UsersSerializer(Profile.objects.get(User.objects.get(pk=serializers.data['id']))) def profile_info(self, obj): # print ('selffff ', serializers) prof_obj = Profile.objects.get(user=User.objects.get(pk=id)) return {'id':prof_obj.id} -
django-redis how to remove key prefix of ":1:"
I set a str below from django.core.cache import cache ... cache.set("cae9ad31b9206a1b5594813b509e1003", "test", timeout=10) it generate a key like this below: :1:cae9ad31b9206a1b5594813b509e1003 how to remove ":1:" ? -
Prevent a user to access a page in some situations or directly
I have an Account Model which have a field is_active(Boolean) by default false, and a Company Model with foreign key to account: class Account(Meta): name = models.CharField(max_length=255) is_active = models.BooleanField(default=False) class Company(Meta): account = models.ForeignKey(Account, related_name='account', on_delete=models.CASCADE) In the get method of CBV I check if user is active an if is not I redirect him to a different url page. # an account can contain multiple users # account is a foreign key on the User model account = self.request.user.account if not account: raise Http404 if not account.is_active: return redirect('accounts:inactive') return account Url: path('inactive/', AccountInactiveView.as_view(), name='inactive'), view for redirect: class AccountInactiveView(TemplateView): template_name = 'accounts/account_inactive.html' I don't want the redirect page/url to be access by anyone directly especially if Account is active field is True. I also receive the following error: 'Account' object has no attribute 'get' -- I tried to put the account check in an AccountMixin (to use it with multiple CBVs) but because in some cases I return redirect will fail. -
Cloudways alternative to host rails and django app
I started to use cloudways.com by moving from private vps. Everything is nice with cloudways (multiple apps on same host, easy application development, domain add, easy ssl management and ftp, ssh access) But only problem with it. I cannot host different kind of applications. Do you know another platform that I can host unlimited app on single host with below features: One-Click application installation (nice to have) Unlimited apps on single host (I have a lot small webapp) Custom domain Easily manage SSL (update with one click or autoupdate) Sftp, Ssh, Remote database access One click backup (nice to have) Staging (nice to have) I'm a developer not devops guy. -
How to select and remove multiple pages in wagtail admin?
In django admin we can select multiple items and then delete them in one action. Is that possible in the wagtail admin or should we delete pages one by one? -
Django rest framework: Listapiview return key:value pair dictionary than an array
I have the following serializer: i am trying to add the key : value representation by overwriting the to_representation method. class IngredientListSerializer(ModelSerializer): class Meta: model = Ingredient fields = '__all__' def to_representation(self, data): res = super(IngredientListSerializer, self).to_representation(data) return {res['id']: res} My view is: class IngredientListAPIView(ListAPIView): queryset = Ingredient.objects.all() serializer_class = IngredientListSerializer The output looks like this: "results": [ { "172": { "id": 172, "name": "rice sevai", } }, { "218": { "id": 218, "name": "rocket leaves", } } ] The output i am looking for is: "results": { "172": { "id": 172, "name": "rice sevai", }, "218": { "id": 218, "name": "rocket leaves", } } -
stream.exceptions.FeedConfigException error
My backend Django REST Framework prints this error. stream.exceptions.FeedConfigException: The following feeds are not configured: 'user'. This could be the cause of a typo, but otherwise you should configure them on the dashboard of this app. Here is my snippet of source code class Post(models.Model, Activity): parent = models.ForeignKey("self", blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) ... @property def activity_actor_attr(self): return self.user I guess I need to create user feed in dashboard. But I don't understand why it's happening. user? feed? Should I put Activity to AUTH_USER_MODEL?? I don't have UserModel and I'm using the default UserModel. :( UPDATE I added user Feed and it solved the problem. And I don't see any row data. I'm totally new in getStream() and need to learn it really fast. -
Concurrency protection is not working
I go bananas here. With my attempts to implement concurrency protection. So I figured out there are 2 ways to do it. Optimistic - basically we add a version field to the record and each save will increase it. So if my current version field is different that one on the disc it means something got modified and I give an error. And the pessimistic approach that means we just lock a record and it will be not possible to edit. I implemented both ways plus concurrency package for Django and nothing works I teas on SQLLite and on Postgres with Heroku. Below is my view method it has both approaches for pessimistic, I lock with transaction atomic using select_for_update and for optimistic I use concurrency django package that increases my version field on each edit and do a simple comparison with on_disc value What I do wrong? Please help? @login_required def lease_edit(request,pk,uri): logger = logging.getLogger(__name__) title = 'Edit Lease' uri = _get_redirect_url(request, uri) with transaction.atomic(): post = get_object_or_404(Lease.objects.select_for_update(), pk=pk) if request.method == "POST": form = LeaseForm(request.POST, instance=post) if form.is_valid(): lease = form.save(commit=False) on_disc= Lease.objects.get(pk=post.id) if on_disc.version > post.version: messages.add_message(request, messages.ERROR, str(lease.id) + "-Error object was modified by another user. … -
Django serializer not save data to database but response is OK
The serializer below don't save changes to database but JSON response from API has new correct values! What is wrong with it? class FieldSerializer(serializers.ModelSerializer): class Meta: model = Field fields = 'id', 'name', 'default' class DocumentSerializer(serializers.HyperlinkedModelSerializer): field = FieldSerializer(many=False, read_only=True) def _save_field(self, instance): field = self.initial_data.pop('field', None) field_ids = field['id'] field = Field.objects.get(pk=field_ids) instance.field = field def save(self, **kwargs): instance = super().save(**kwargs) self._save_field(instance) -
Django query on related model
I have models like below class Scheduler(models.Model): id = <this is primary key> last_run = <referencing to id in RunLogs below> class RunLogs(models.Model): id = <primary key> scheduler = <referencing to id in Scheduler above> overall_status = <String> Only when the scheduler reaches the scheduled time of the job, RunLogs entry is created. Now I am querying on RunLogs to show running schedules as below. current = ResourceLog.objects\ .filter(Q(overall_status__in = ("RUNNING", "ON-HOLD", "QUEUED") | Q(scheduler__last_run__isnull)) The above query gives me all records with matching status from RunLogs but does not give me records from Scheduler with last_run is null. I understand why the query is behaving so but is there a way to get records from scheduler also with last_run is null ? -
What would be a good approach to construct docker containers for nginx, uwsgi, django
I have an approach that use a base OS image to construct nginx, uwsgi, django all inside a container for the purpose to fast deploy a website on a cloud service. And I also successfully building a reverse proxy to point to different django apps, but still inside one container. This approach has the drawback that, when I update one of the services or apps, I need to completely destroy the whole container and create a new container with all services. Therefore, I want to construct for nginx, uwsgi each with one container, for each django app a container. In short, I want to separate apps and services each with a container. Most of the tutorials online deploy such combinations inside one container. So my question is what would be the best approach to do so? For services such as nginx, uwsgi, should I construct them without a base OS image but simply just the service image, or I should construct them each with a base OS image and then add the service on top? Also, for my Django apps, should I construct for each app with a base OS image or just start base with python image? -
Django: apps.get_models() yields models from unittests
If I call this django method, in a test, it yields a lot of models which are not installed. These models are from other apps test code: apps.get_models() For example I get MROBase1 from the django package polymorphic test code. -
Ionic Framework Posting to Django Rest Framework Using HTTP Requests
I'm trying to create a new user in my Ionic app using Django as the backend. So far I can create a user no problem using Postman, but when I try to make an HTTP post request through my app I get the following error: {"password":["This field is required."],"username":["This field is required."]}. I am passing the username and password field to my Django app, but for some reason it doesn't register it. Is my post call wrong? DJANGO APP CODE serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True), source="userprofile.languages") class Meta: model = User fields = ('first_name', 'last_name', 'email', 'username', 'password', 'languages') def create(self, validated_data, instance=None): profile_data = validated_data.pop('userprofile') user = User.objects.create(**validated_data) user.set_password(validated_data['password']) user.save() UserProfile.objects.update_or_create(user=user, **profile_data) return user views.py @api_view(['POST']) @permission_classes((AllowAny,)) def create_user(request): serialized = UserSerializer(data=request.data) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) IONIC APP CODE http.ts register(username, password, email, first_name, last_name, languages) { let url = "https://www.example.com/api/create_user/"; let headers = new Headers() headers.append("Content-Type", "application/x-www-form-urlencoded"); return this.http.post(url, {"first_name": first_name, "last_name": last_name, "email": email, "username": username, "password": password, "languages": languages }, {headers: headers}) .map(res => res.json()); } register.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { HttpProvider } …