Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django does not redirect from one view/url to another
I will start with explanation of what I want to achieve. Basically I want to display in my view(prefs) an array items on a page that each item looks like button and if clicked it redirects to a view(results) and passes an argument(i.e itself) My views.py look like this def prefs(request): if request.method == 'POST': for i in user_queryset(request): #this function returns an array if i in request.POST.values(): return redirect(reverse('results',kwargs={'UserChoice':i})) elif not request.user.is_authenticated(): return HttpResponse('Please login or sign-up to use this feature') else: uid = request.user return render(request,'test.html',{'form':user_queryset(request,uid)}) def results(request,UserChoice): if request.method =='GET': return render(request,'test2.html',{'objects':request_places(request,UserChoice)}) else: return HttpResponse('Hello, World!') my urls.py url(r'places/$',views.prefs,name='prefs'), url(r'^places/results/(?P<UserChoice>[^\/]*)/$', views.results, name='results') and my templates <ul> <li> <form role="form" action="" method="post"> {% for obj in form %} <!--<input type="text" name="{{ obj }} ">--> <input type="submit" value="{{ obj }}"> </form> </li> {% endfor %} </ul> -
django template white page
Help me after add my {% extends "menu.html" %> the rest of my page is white I can not see my content anymore resultat -
Issue with Django logout URL redirection
I have configured login and logout redirect setting in Django settings as below - LOGOUT_REDIRECT_URL = '/login/' LOGIN_REDIRECT_URL = '/locations/' However, after logging out the redirection is done on the next= parameter, ie., the url is redirected to the same page from where logout is clicked. For the reference, here is login/logout URL from my urls.py - url(r'^', include('rest_framework.urls', namespace='rest_framework')), PS: I am using Django 1.11 & DRF 3.7.3 -
Django testing form with modelchoicefield
I amended a form to make a ModelChoiceField so that users can only select categories that they have set up. This is working correctly when I run my app in the browser but fails the test (in that it says the form is not valid), which passes if you remove the ModelChoiceField and allow it to display all categories from the model. I am happy that the code for the form works as expected and required in the browser; it is the test case that I would like to fix. I imagine there is something obvious I can't see because I have looked at it too many times. Can anyone help please? Extract from test case def setUp(self): user = User.objects.create(username='user', password='') self.category = Category.objects.create(id=1, user=user, title='category1') self.myitem = MyModel.objects.create(id=1, user=user, title='title1', amount=10, category=self.category) def test_form_validation_with_valid_data(self): user = User.objects.get(username='user') now = timezone.now() form = MyModelForm({'title': 'title1', 'category': 1, 'amount': 100, 'date': now,}, user) self.assertTrue(form.is_valid()) Extract from forms.py class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ('title', 'category', 'amount', 'date',) category = forms.ModelChoiceField(queryset=None) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(MyModelForm, self).__init__(*args, **kwargs) self.fields['category'].queryset = Category.objects.filter(user=self.user) -
Django-carousel bootstrap
Since i am new in django stuff i finally manage to add carousel slider in my website but my slider is not working. It stucks in first image and doesn't slides to another image. However viewing source in my local port shows all image path but in red text. Please help Here is my code base.html <div class="container"> <div id="carouselExampleIndicators" class="carousel slide" data- ride="carousel"> <!-- Indicators--> <ol class="carousel-indicators"> {% for item in slider %} <li data-target="" data-slide-to="{{item.id|add:-1}}" {%if forloop.first %}class="active"{%endif%}></li> {% endfor %} </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> {% for item in slider %} {%if forloop.first %} <div class="carousel-item active">{%else %}<div class="carousel-item">{%endif%} <img class="d-block w-100"src="media/{{item.slider_image}}" alt="{{item.display_title}"> <div class="carousel-caption d-none d-md-block"> <h3>{{item.display_title}}</h3> </div> </div> {%endfor%} </div> <!--left and right Controls --> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> </div> source view code in my local port <div class="container"> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <!-- Indicators--> <ol class="carousel-indicators"> <li data-target="" data-slide-to="3" class="active"></li> <li data-target="" data-slide-to="4" ></li> <li data-target="" data-slide-to="5" ></li> <li data-target="" data-slide-to="6" ></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100"src="media/slider/2017/12/04/DAKU.png" alt="{{item.display_title}"> <div class="carousel-caption d-none … -
Optimal project organization and querysets
I have 2 models Company and Product with FK on Product: class Product(Meta): company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) In case of a View that will gather company products what is the optimal approach(use infor form both models): 1) add the View in companies app and as queryset use: Company.objects.prefetch_related('products').get(pk=company_pk) 2) add the View in products app and as queryset use: Product.objects.select_related('company').filter(company=company_pk) What about ordering can be chained with prefetch or select ? -
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 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 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 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.