Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django TemplateView use pagination and getting only 1 result
i want to make pagination out of filter_alert only. And i also get only the last result out of filter_alert. I will explain more below the code. This is my code in views.py class TestView(FormView, TemplateView): template_name = 'home/main.html' context_object_name = 'pages' paginate_by = 10 form_class = DomainsForm def get_context_data(self, **kwargs): context = super(TestView, self).get_context_data(**kwargs) list_tables = Domains.objects.all() context['lists'] = list_tables tbls_id = list_tables.exclude(status=0).values_list('id', flat=True) context['alerts_list'] = Alerts.objects.all() data = [] for row_id in tbls_id: cron_info = get_cron_info(row_id) data.append(cron_info) context['data'] = simplejson.dumps(data) tbl = Domains.objects.get(id=row_id) t_pages = create_pg("Pages_" + tbl.tablename) query_pages = t_pages.objects.all() context['pages'] = query_pages get_alerts = create_alerts('Links_' + tbl.tablename + '_Alerts') filter_alert = get_alerts.objects.all() context['all_alerts'] = filter_alert return context So in the table Domains i have 3 id's, 1 of them has the status=0. I want to get the other 2 id's and pass them through the for loop. But when i pull out the results in the template...i only get the last id. I also want to implement the pagination...i usually use this code...but it doesn't work in the TemplateView. all_alerts = get_alerts.objects.all() page = request.GET.get('page', 1) paginator = Paginator(all_alerts, 10) try: details = paginator.page(page) except PageNotAnInteger: details = paginator.page(1) except EmptyPage: details = paginator.page(paginator.num_pages) context['all_alerts'] = … -
searching multiple elements in different django models using haystack search
Any help on how to search multiple elements input in Django separated by comma. I have two fields of the same names in all my models. I got this ajax.js code: $(function(){ $('#search').keyup(function(){ $.ajax({ type: "GET", url: "/predictgene/search/", data: { 'search_text' : $('#search').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search-results').html(data); } My search index. I have about 25 search indexes, I just need to be able to search multiple input text separated with a comma or space. The results should show the name of the models and all the elements search for. my search_index.py class ArthrogryposisIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) gene = indexes.CharField(model_attr='gene') # prediction = indexes.CharField(model_attr='prediction') # pub_date=indexes.DateTimeField(model_attr='pub_date') content_auto = indexes.EdgeNgramField(model_attr='gene') def get_model(self): return Arthrogryposis def index_queryset(self, using=None): """used when the entire index for model is updated.""" return self.get_model().objects.all() -
how to handle httpresponseredirect
test2/urls.py from django.conf.urls import url from .import views from .forms import forms urlpatterns=[ url(r'^$',views.index,name='index'), url(r'^thankyou/$',views.thankyou,name='thankyou') ] test1/urls.py from django.contrib import admin from django.conf.urls import url , include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test2/',include('test2.urls')), ] views.py this view should redirect to /test2/thankyou/ but why it is going to /thankyou and what to do enable the view given by redirect method from django.shortcuts import render from django.http import HttpResponseRedirect,HttpResponse from .forms import Get_name # Create your views here. def index(request): if request.method == 'POST': form = Get_name(request.POST) if form.is_valid(): return HttpResponseRedirect('/thankyou/') else: form = Get_name() return render(request, 'test2/name.html' , {'form':form}) def thankyou(request): return HttpResponse('sai chaitanya') name.html after submitting the form it should redirect to test2/thankyou but it is going to /thankyou. <form action="/thankyou/" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> forms.py from django import forms user_choice =[('space',''),('passenger','Passenger'),('driver','Driver')] class Get_name(forms.Form): user_name = forms.CharField(label='user name',max_length='50',required=True) pass_word1 = forms.CharField(widget=forms.PasswordInput,max_length='20',label='Password') pass_word2 = forms.CharField(widget=forms.PasswordInput, max_length='20', label='Confirm Password') email = forms.EmailField(label='email',max_length='100') mobile = forms.CharField(label='contact number ',widget=forms.NumberInput,max_length='10') address = forms.CharField(label='Address',max_length='100') user_type = forms.CharField(label='select user type',widget=forms.Select(choices=user_choice)) -
Accessing JSON key & value passed as variables in Django views
What i am trying to do ? I am trying to check if the entered email or username already exists in the database by passing JSON Key and Value as variables from signup form ( using ajax ) to Django views. The Key holds either the 'username' or 'email' and Value holds the required value (eg: 'dave' or 'example@gmail.com'). What is the problem ? For some reason Django always return false even for the user that is already registered in the database. jQuery: function validateInputs(inputNameId){ var value = $(inputNameId).val(); var inputName = inputNameId.replace("#input",""); if (inputName == 'Username' || inputName == 'Email') $.ajax({ type: 'GET', url: '/authenticate/register/', data: { 'inputName': inputName, inputName: value, // passing Key & Value as variables 'is_taken': false }, dataType: 'json', success: function(data){ console.log(data['is_taken']); }, error: function(xhr){ alert("An error occured: " + xhr.status + " " + xhr.statusText); } }); } function validateSignUpModal(){ $("#inputEmail, #inputUsername, #inputPassword, #inputConfirmPassword").change(function(){ var $this = '#' + $(this).attr('id'); validateInputs( $this ); }); } views.py: class registerForm(View): form_class = signupForm def get(self, request): data = {} inputName = request.GET.get('inputName', None); inputVal = request.GET.get(inputName, None); // this returns None why ? Isn't that how you access JSON Value from Key which are passed as … -
SEO in Django. Can Django give better results than other language and framework
Does Django support SEO. can django give dynamic urls like abc.com/mobile/smart if yes then it will give effective results like other give. I'm new to Django and python as well. -
Invalid filter error in django custom template filter
I'm trying to create a custom template filter but, getting Invalid filter error. TemplateSyntaxError at /attainment/reportcard/ Invalid filter: 'get_item' Request Method: POST Request URL: http://127.0.0.1:8000/attainment/reportcard/ Django Version: 1.11.5 Exception Type: TemplateSyntaxError Exception Value: Invalid filter: 'get_item' Exception Location: /media/itsd/ITSD/ROFI/Projects/Rise/venv/lib/python3.5/site-packages/django/template/base.py in find_filter, line 606 Python Executable: /media/itsd/ITSD/ROFI/Projects/Rise/venv/bin/python Python Version: 3.5.2 I've created a filter in and registered. template_filters.py from django.template.defaulttags import register # Custom template filter to get data from a dictionary using key in template @register.filter def get_item(dictionary, key): return dictionary.get(key) And I've used the filter in the template as follows. <tbody> {% for subject in subjects %} <tr> <td>{{ subject|get_item:"subject" }}</td> <td>{{ subject|get_item:"efffort" }}</td> <td>{{ subject|get_item:"homework" }}</td> <td>{{ subject|get_item:"marks" }}</td> <td>{{ subject|get_item:"grade" }}</td> </tr> {% endfor %} </tbody> What am I missing ?? N.B: I've followed this answer. -
Pass data to widget in Django
I am new to Django. I have a form with 3 fields where the third one has a custom widget. In the relevant HTML of the widget I want to access some data which is retrieved in my view in which this widget is going to be used. How can I do that? myView: def create(request): bounds = // some data retrieved from somewhere form = forms.MyForm(bounds) return render(request, 'myHTML.html', { 'form': form, myForm: class myForm(forms.Form): //1st and 2nd forms position = PointField(label=_("position"),widget=myWidget) and myWidget: class myWidget(mainWidget): template_name = 'utils/my_widget.html' and mainWidget has some more thing which does not matter much I believe here. Now how can I pass retrieved data in myForm to my_widget.html? I have check this answer but that is not working for me: similar answer -
Django HttpResponse makes RANDOMLY a response blank or empty string
Need help please. I am passing a value to HttpResponse (of Django) at the backend and when I hit the request url, am getting the same value back from HttpResponse. But RANDOMLY HttpResponse gives the blank response or empty string for the same request url. Can you please suggest why or how to fix this random issue of HttpResponse? I tried JsonResponse, subclass of HttpResponse but yet the same behaviour of blank response randomly! My code sample is as below: views.py def getCorrectedDate(request): import datetime date = getStringDateAsDatetime(request.GET['date']) z = DateManipulation(datetime.date(2017,11,1),datetime.date(2018,11,1)) print(int(round(time.time() * 1000))); correctedDate = z.getCorrectedDate(date) response = HttpResponse(correctedDate) print(response) return response response prints (for example "2017/12/13") correctly all the times at back end even when HttpResponse gives blank response (i.e. _body="", instead of _body="2017/12/13") data-service.ts getCorrectedDate(date: string): Observable<Response> { return this.http.get(this.getCorrectedDateUrl + '?date=' + date, {headers: this.HEADERS}).map((res: Response) => this.handleData(res)) .catch((error: any) => Observable.throw(error.json().error || 'Server Error')); } handleData(res: Response){ console.log(res); } Thanks in advance, would appreciate your replies. -
Sharding existing postgresql database with PostgresXL
We want to shard our PostgreSQL DB, due to high disk load. Firstly, we looked at django-sharding library, but: Very much rewriting in our backend Migrating all tables to 64-bit primary keys is hard work on 300-400gb tables Generating ids with Postgres Specific algorithm makes it impossible to move data from shard to shard. More than that, we have a large database with old ids. Updating all of them is a big problem too. Generating ids with special tables makes us do a special SELECT query to main database every time we insert data. We have high write load, so it's not good. Considring all these, we decided too look on Postgres database sharding solutions. We found 2 opportunities - Citus and PostgresXL. Citus makes us change data format too much and rewrite a big bunch of backend at the same time, so we are about to try PostgresXL as more transparent solution. But reading the docs, I can't understand some things and will be greatfull for recomendations: Are there any other sharding workarounds except for Citus and PostgresXL? It would be good not to change much in our database on migrating. Some questions about PostgresXL: Do I understand correctly, … -
Serving images asynchronously using django and celery?
I have a django app that serves images when a certain page is loaded. The images are stored on S3 and I retrieve them using boto and send the image content as an HttpResponse with the appropriate content type. The problem here is, this is a blocking call. Sometimes, it takes a long time (few secs for the image of few hundred KBs) to retrieve the images and serve them to the client. I tried doing converting this process to a celery task (async, non-blocking), but I am not sure how I can send back the data (images) when they are done downloading. Just returning HttpResponse from a celery task does not work. I found docs related to http callback tasks in an old celery docs here, but this is not supported in the newer celery versions. So, should I use polling in the js? (I have used celery tasks in other parts of my website, but all of them are socket based) or is this even the right way to approach the problem? Code: Django views code that fetches the images (from S3 using boto3): (in views.py) @csrf_protect @ensure_csrf_cookie def getimg(request, public_hash): if request.user.is_authenticated: query = img_table.objects.filter(public_hash=public_hash) else: query … -
Django return JsonResponse and catch data in ajax request
Here is my view. I am returning JsonResponse to ajax request where catching incoming data from my view 'line_product_total': total, and other contexts def get(self, request, *args, **kwargs): cart = self.get_object() product_id = request.GET.get('product') delete_product = request.GET.get('delete', False) product_added = False if product_id: product_instance = get_object_or_404(Product, id=product_id) amount = request.GET.get('amount', 1) try: if int(amount) < 1: delete_product = True return HttpResponse('IntegrityError', delete_product) except: raise Http404 cart_product, created = CartProduct.objects.get_or_create(cart=cart, product=product_instance) if created: product_added = True if delete_product: cart_product.delete() else: cart_product.amount = amount cart_product.save() if not request.is_ajax(): return HttpResponseRedirect(reverse('e_commerce:cart')) # return cart_product.cart.get_absolute_url if request.is_ajax(): try: total = cart_product.line_product_total except: total = None data = \ { 'deleted': delete_product, 'product_added': product_added, 'line_product_total': total, } return JsonResponse(data) cart = Cart.objects.get(pk=cart.pk) return render(request, 'sales/cart.html', {'cart': cart}) js $('.type_number').change(function () { var product = $(this).next('input[type=hidden]').val(); var amount = $(this).val(); var data = { product:product, amount: amount }; console.log(data); $.ajax({ type: 'GET', url: '{% url "e_commerce:cart" %}', data: data, success: function (data) { $('#jquery-message').text('Added' + data.product_added + 'Deleted' + data.deleted); if (data.deleted) { $('#product-'+product).fadeOut; } else { $('#product-line-total-'+product).text(data.line_product_total); } }, error: function(response, error) { $('#add-form').submit() } }) }) template <form action="." method="GET"> <h4 id="product-line-total-{{ product.id }}">{{ product.line_product_total }}</h4> <input class="type_number" style="text-align: center;margin-left: -50px;" title="" type="number" name="amount" … -
django - csrf protection - markdown2
In some of my blog posts using django and markdown2, I am trying to include a form as follows: views.py: def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) if not instance.published: raise Http404 return render(request, "posts/post_detail.html", {'instance': instance}) My template post_detail.html contains a {{ instance.get_markdown }} variable: ... {{ instance.get_markdown }} ... models.py: import markdown2 class Post(models.Model): ... text = models.TextField(verbose_name=_("Text")) ... def get_markdown(self): return mark_safe(markdown2.markdown(self.text)) Example for a saved text in Post: ### Example <form method = "POST"> {% csrf_token %} First name:<input type="text" name="firstname"> <input type="submit" value="Submit"> </form> This way, the page simply shows the string "{% csrf_token %}" within the form. How can I render the post with csrf protection? -
How can we use html <input type= ""> for Django model form?
using this for django model form, we cant create beautiful front end. <form method="POST" action=""> {% csrf_token %} <div class="esor"> Name: {{form.Name}}<br> Class: {{form.Class}}<br> Publisher: {{form.Publisher}}<br> </div> <input type="submit" value="submit"> </form> Isn't there any ways so we can use html code like: <form method="GET" action="#"> <input type="text" name="name" placeholder="Name of book"> </form> instead of {{form.Name}} or {{form.as_p}} -
Displaying image from foreignkey in Admin Panel in Django
I have in project two classes - Photo and Prescription inside models.py file which are related each other with foreign key. Here is part of the code: class Photo(models.Model): name = models.CharField(max_length=100,null=False) photo = models.ImageField(upload_to="photos/",null=True) def photo_tag(self): return '<a href="/media/{0}"><img src="/media/{0}"></a>'.format(self.photo) photo_tag.short_description = 'Photo of prescription' photo_tag.allow_tags = True class Prescription(models.Model): description = models.CharField(max_length=100,null=True) photo = models.ForeignKey(Photo, related_name='related_photo',null=True) def __str__(self): return self.description And my Admin.py class PhotoAdmin(admin.ModelAdmin): list_display = ('name', 'photo_tag') fields = ('name','photo','photo_tag') readonly_fields = ('photo_tag',) admin.site.register(Photo,PhotoAdmin) class PrescriptionAdmin(admin.ModelAdmin): list_display = ('get_photo') fields = ('photo','description') model = Prescription def get_photo(self, obj): return obj.photo.photo_tag get_photo.short_description = 'Photo of prescription' admin.site.register(Prescription,PrescriptionAdmin) Question is, when I open prescriptions list instead of photo in the Photo of prescription field shows following message. <bound method Photo.photo_tag of <Photo: Photo object>> How real photo could be described there? -
Queryset filter using Case/When for Model field, not field value
I would like to combine two querysets, or better, make only one using the Case/When syntax for a specific case. I have seen in the documentation that it can be use for queryset filtering, not only annotate, which is exactly what I need. However, I want to use the Case/When for the model field itself, not the value of the field. Here is my code : self.in_stock_lines = basket.lines.filter(product__product_class__track_stock=True, is_customized=False) Thing is, a product can be either a child or a standalone product. If it is a child, the field I must filter on is product__parent__product_class__track_stock, whereas if it is a standalone, it stays product__product_class__track_stock as in my initial queryset. Is there a way to do this ? Or do I have no choice but combine the two querysets using itertools.chain() for example ? -
Django shell printing everything twice
I have something that is happening in my django shell that I cannot explain and do not know how to fix; def get_answer_dict(self, format = None, *args,**kwargs): current_user = MyUser.objects.get(id = self.kwargs['pk2']) #current_user print(current_user) survey_team = Survey.objects.get(name= 'Survey Raphael') #survey team (to change to final one) current_response = ResponseModel.objects.filter(user = current_user, survey = survey_team)[0] #current response #print(current_response) answer_list = current_response.answers.all() #print(answer_list) answer_dict = [] for answer in answer_list: ans_body = answer.body ans_json = json.loads(ans_body) answer_dict.append(ans_json) return answer_dict The thing is that in my django shell the user is printed twice... Do you have an idea why ? -
Django REST API populate only selected fields from Many to many field
I have a working API in my project that look something like this : { "id": 1, "project_name": "Project A", "user": [ { "id": 3, "employee_id": "001", "official_name": "RAY PAlMER", "nick_name": "RAY", "date_of_birth": "1965-08-25", "gender": "1", "race": "CAUCASIAN", "food_pref": "Vegetarian", } ] } The user field is a foreign key field and its populating everything from its source model called Employee. My question is how can I populate the user many to many field with only several field that I wanted to get from the Employee Model. For example I just want to populate only a user id, official name, and gender, therefore the output should be something like this { "id": 1, "project_name": "Project A", "user": [ { "id": 3, "official_name": "RAY PAlMER", "gender": "1", } ] } Below is my source code : Project Model : class Project(models.Model): user = models.ManyToManyField(Employee, blank=True) Employee Model : class Employee(models.Model): official_name = models.CharField(max_length=200, null=True, blank=True) gender_choice = ( ('male', 'Male'), ('female', 'Female') ) gender = models.CharField(max_length=10, choices=gender_choice, null=True, blank=True) Serializer : class MarketingReportSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ('id', 'project_name','user') depth = 1 Any help is much appreciated thanks! API : class MarketingReportAPI(APIView): def get(self, request): all_projects = Project.objects.all() … -
Using DateTimeShortcuts.js in main admin panel
I want to be able to use the Django date widget in the main admin panel. It is outside any model class. How can I load all the relevant js and the css libraries in the main page? (I'm using Django 1.11.3) Thank you -
How to block same object reference for Foriegn key in same table in Django?
I have a Model which has a self foriegn key. class Employee(AbstractUser): manager = models.ForeignKey('self', on_delete=models.SET_NULL, related_name=_('manger'), null=True) Now when i add this Model to admin site and try to update an employee users's can set themself as their own manager. So if i am trying to update employee ID #1, I dont want employee ID #1 to be displayed in the managers dropdown. Additional Question I know that i can add clean method that validates this condition in my Update form, however i do not know how to get the current object ID to check against manager ID. class EmployeeChangeForm(UserChangeForm): class Meta: model = Employee fields = '__all__' def clean_manager(self): # An Employee Cannot have himself assigned as a manager # how do i get the id of Current Employee here ? mgr = self.cleaned_data["manager"] return mgr The above approach will not allow the current user to block employee from setting himself as setting as his manager however, the employee will still show in the dropdown of the manager field. I would prefer if the current employee does not show in the dropdown at all. Is there a way to do that ? -
Django-signal receiver doesn't work although connected in the ready() method
I'm new in Django, maybe my question has a simple answer, but I'm at deadlock. My signal code lives in signals.py, I use @receiver. According to documentations, I imported the signal submodule inside ready() in apps.py. But it doesn't work =( Could anybody help me? N.B. If I write my signal code inside models.py everything works well. Code: signal.py from django.db.models.signals import post_delete from django.dispatch import receiver import os from .models import ProductImage def delete_image_from_storage(path): if os.path.isfile(path): print(path) os.remove(path) @receiver(post_delete, sender=ProductImage) def post_delete_image(sender, instance, **kawargs): if instance.photo: print(instance.photo.path) delete_image_from_storage(instance.photo.path) apps.py from django.apps import AppConfig class ProductsConfig(AppConfig): name = 'products' def ready(): import products.signals settings.py INSTALLED_APPS = [ ..., 'products', ..., ] -
Exhaustive list of cases when django save signals are not called
According to django docs , pre_save and post_save are called Sent before or after a model’s save() method is called. The docs for QuerySet tell that QuerySet.update() and QuerySet.bulk_create() do not call Model.save() Thus, QuerySet.update() and QuerySet.bulk_create() dont call pre_save and post_save. Question : Is that all the cases where objects are written to database without signals being called? -
How can I combine two views and two forms into one single template?
I have two separate class-based views and would like to keep their functionality, and have the two CBVs point to the same template (I'm trying to bring two separate forms into a single page). More specifically, I am trying to subclass/combine this email view, and this password change view, so that I can have them point to the same template, as I ultimately would like both forms on the same page. I've attempted to do this by subclassing them into my own views: class MyEmailUpdateView(LoginRequiredMixin, EmailView): template_name = 'account/account_settings' success_url = reverse_lazy('settings') def form_valid(self, form): return super(SettingsUpdateView, self).form_valid(form) class MyPasswordUpdateView(LoginRequiredMixin, PasswordChangeView): template_name = 'account/account_settings' success_url = reverse_lazy('settings') def form_valid(self, form): return super(SettingsUpdateView, self).form_valid(form) But I am now finding out due to errors, one by one, that it appears nothing from the parent class is actually transferred over to my custom class unless I manually bring it in(success_url, methods, etc). Even then, the code from the original classes that I am subclassing are pointing elsewhere. SO, when combining these two views, do I need to copy all of the original code into my custom sublassed views? Is this the proper way to accomplish it? How can I combine these two views? … -
I have a choice option in my models but everytime I open one of my customers they get reset
Everytime I open an existing customer again the field value gets changed also how to prevent that from happening Region=( ('-','-'), ('us','US'), ('emea','EMEA'), ('apac','APAC'), ('others','OTHERS'), ) name = models.CharField(max_length=1000, verbose_name="Customer Name") Region =models.CharField(max_length=1000,choices=Region,) -
celery django works fine, but logs are flooded with weird lines
So I've followed these two tutorials to integrate celery in my django project. It's working nicely, but my redis server terminal screen is flooded with the following, dozens of them for each time the task runs: [2017-12-13 10:58:36,024: INFO/ForkPoolWorker-1] in <ws2:release-group>, uncaught attribute type-id [2017-12-13 10:58:36,025: INFO/ForkPoolWorker-1] in <ws2:release-group>, uncaught attribute type-id [2017-12-13 10:58:36,025: INFO/ForkPoolWorker-1] in <ws2:release-group>, uncaught attribute type-id [2017-12-13 10:58:36,025: INFO/ForkPoolWorker-1] in <ws2:release-group>, uncaught attribute type-id [2017-12-13 10:58:36,025: INFO/ForkPoolWorker-1] in <ws2:release-group>, uncaught attribute type-id [2017-12-13 10:58:36,025: INFO/ForkPoolWorker-1] in <ws2:release-group>, uncaught attribute type-id [2017-12-13 10:58:36,026: INFO/ForkPoolWorker-1] in <ws2:release-group>, uncaught attribute type-id My task is defined as such in subapp/tasks.py: from celery.decorators import task from celery.utils.log import get_task_logger from .models import Artist @task(name="refresh_db_task") def refresh_db_task(): return Artist.refresh_from_mb() And called as such from one of the views: refresh_db_task.delay() Interestingly, release-group is similar to the name of one of my models, ReleaseGroup. I thought that maybe it's a print statement somewhere in Artist.refresh_from_mb() (a class-method), but that's not the case. I've tried searching SO for similar issues but could find none. -
onclick="history.back() don't work in Safari and IE
this simple line of code: Back works good for Chrome and Firefox, but not for Safari and IE..., for IE it normal case, only very strange persons use it, but why Safari ? Note: the whole project is done with django 1.45