Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to simplified these code with for loop?
Here is my code: phones = Customer.objects.filter(active=True).values('name')\ .annotate(count = Count('phone',filter=Q(phone__model__icontains=model_list[0])) .annotate(count1 = Count('phone',filter=Q(phone__model__icontains=model_list[1])) .annotate(count2 = Count('phone',filter=Q(phone__model__icontains=model_list[2])) .annotate(count3 = Count('phone',filter=Q(phone__model__icontains=model_list[3])) .annotate(count4 = Count('phone',filter=Q(phone__model__icontains=model_list[4])) ........ html {% if phones %} {% for phone in phones %} <tr> <td>{{ phone.name }}</td> <td>{{ phone.count }}</td> <td>{{ phone.count1 }}</td> <td>{{ phone.count2 }}</td> <td>{{ phone.count3 }}</td> <td>{{ phone.count4 }}</td> </tr> {% endfor %} {% enfif %} My model_list still got many model, what should I do to simplify these using for loop? If my model_list has 100 model, these will be very complicated. I've tried this: for i in range(len(model_list)): phone= Customer.objects.filter(active=True).values('name')\ .annotate(count = Count('phone',filter=Q(phone__model__icontains=model_list[i])) html {% if phones %} {% for phone in phones %} <tr> <td>{{ phone.name }}</td> <td>{{ phone.count }}</td> </tr> {% endfor %} {% endif %} But the result is not what i want, beacause i only get one of the data. For example : model_list[0] -
Implementing multi layer role on Django
Working with django Group and Permission. Normally works fine. Now want to add sub admin who can give permission only particular model. How to implement? -
Django forms: how to show only objects associated with user in dropdown
I am a vet hospital, with class Pet and class Records. Each pet can have many records, i.e. everytime it visits the hospital it gets a new record. At the moment, my form shows all the pets ever associated with my app (please view https://i.stack.imgur.com/8j7V8.png). I want only the user's registered pets to appear (why would Bob be bringing a stranger's cat to the vet?) View to add a record: @login_required(login_url="/accounts/login/") def record_create(request): #this line retrieves Pets only belonging to the user logged in pets = Pet.objects.filter(author=request.user) if request.method == 'POST': form = forms.CreateRecord(request.POST, request.FILES) print(form) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('records') else: form = forms.CreateRecord() return render(request, 'records/record_create.html', {'form': form,}) forms.py class CreateRecord(forms.ModelForm): class Meta: model = models.Record fields = ['feedID', 'amountLeftOver', 'amountDispensed', 'additionalInfo', 'selectPet'] How do I get the selectPet dropdown to show only Bob's registered pets? Thanks for your time! -
Get Django variable in Javascript : undefined value
I have a little issue and I don't overcome to solve it. I have a list of Django objects generated in my views.py file and I would like to display these variables in my Javascript part. I get the list in my Javascript code, but each variable are 'undefined'. In my views.py file, I have : context['results2'] = SubMethod.objects.values_list('name', flat=True).all() Then, in my HTML/JS part : function get_sub_method_options(keep_cur) { var sel_option = $('select#id_method-group').find("option:selected"); var sel_val = sel_option.val(); if (!sel_val) { $("select#id_method-sub_method").empty(); var all_sub_methods = "{{ results2 }}"; console.log(all_sub_methods.name); for (var i = 0; i < all_sub_methods.length; i++) { $("select#id_method-sub_method").append('<option value="' + all_sub_methods[i].id + '">' + all_sub_methods[i].name + '</option>'); //here add list of all submethods } return; } data = { 'test_method': $('select#id_method-test_method').find("option:selected").val(), 'group': sel_val }; $.ajax({ method: "GET", url: '{% url 'ajax_method_submethod' %}', data: data }).done(function (result) { reset_select('id_method-sub_method'); for (var i = 0; i < result['results'].length; i++) { if (keep_cur > 0 & keep_cur == result['results'][i].id) $("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '" selected>' + result['results'][i].text + '</option>'); else $("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '">' + result['results'][i].text + '</option>'); } ; }); } As you can see, I pick up my context variable result2 in this part : if (!sel_val) … -
LinkedIn OAuth2 calling from Django..not working
When I click the LinkedIn Auth link, I am getting this usa url and the document says linkedin.com/oauth2/auth... https://www.linkedin.com/uas/oauth2/authorization?client_id=xxxl&redirect_uri=http:xxx/auth/complete/linkedin-oauth2/&state=xxxEfQE01&response_type=code&scope=r_basicprofile+r_emailaddress In settings.py AUTHENTICATION_BACKENDS = ( 'social_core.backends.linkedin.LinkedinOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'keys...' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = 'secret...' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] MIDDLEWARE_CLASSES = [... ... 'social_django.middleware.SocialAuthExceptionMiddleware', ... ] INSTALLED_APPS = [... 'social_django', ...] In html <a href="{% url 'social:begin' backend='linkedin-oauth2' %}">login with LinkedIn Are settings not correct? -
Django - Is the path to my socket correct for nginx configuration
This is in my site1_nginx.conf which is present in the folder /etc/nginx/sites-enabled Now in my site1_nginx.conf , I specified the following upstream django { server unix:/home/ec2-user/FooVenv/FooWeb/site1.socket; # for a file socket } The path to my socket file is /home/ec2-user/FooVenv/FooWeb/site1.socket; However I am not sure if I specified it correct most of the samples I have seen have three leading ///. Currently I am getting the error 2018/11/26 08:40:24 [emerg] 1253#0: invalid host in upstream "/home/ec2-user/FooVenv/FooWeb/site1.socket" in /etc/nginx/sites-enabled/site1_nginx.conf:6 2018/11/26 08:41:37 [crit] 1276#0: *1 connect() to unix:/home/ec2-user/FooVenv/FooWeb/site1.socket failed (13: Permission denied) while connecting to upstream, client: 71.231.182.18, server: qiggz.com, request: "GET /admin/ HTTP/1.1", upstream: "uwsgi://unix:/home/ec2-user/FooVenv/FooWeb/site1.socket:", host: "www.foo.com:8000". I have changed the actual web address to foo for security. Anyways I launched my uwsgi using this uwsgi --socket site1.socket --module main.wsgi --chmod-socket77 -
How to integrate Dialogflow with Django python and consume RESTful APIs?
Good day everyone, I am currently developing a chatbot using Google's Dialogflow and I am really in need of help. I have already seen How to integrate Dialogflow with Django (Python)? but I am still confuse and I have no idea what to do next. Our Django project has already been set up and I have already created my agent in Dialogflow, I also learned how to use ngrok so to connect Dialogflow to fulfillment/webhook. I am new to Django python as well and these are just the things that I've done so far. I've already searched almost, if not all, tutorials/articles/videos on how to integrate Dialogflow to Django python with RESTful APIs and I found none on how to do it. Most tutorial uses Flask and NodeJS as their backend. Although this tutorial uses Flask https://www.pusher.com/tutorials/chatbot-flask-dialogflow/, I tried doing it just to have an idea on how to integrate dialogflow to a backend and call RESTful APIs. I manage to replicate what has been done in the tutorial, but unfortunately, I didn't understood the coding part in the backend or the code in setting up the webhook as I am very new to it. I am really lost right … -
how to change automatically django Formset with each iteration
I would like my formset to change automatically with each iteration but alas it is not the case, it only takes into account the last added value. views.py : class VenteFormView(View): VenteFormSet = formset_factory(VenteForm) template_name = "venteH.html" def get(self, request): return render(request, self.template_name, {'form': self.VenteFormSet()}) def post(self, request, totalvente=0, totalarticle=0): vente_formset = self.VenteFormSet(self.request.POST,error_class=ParagraphErrorList) #try: if vente_formset.is_valid(): for temp in vente_formset: vente =temp.save(commit=True) article = vente.id_article print('article au depart :',article) print('quantité article au depart :', article.quantite) entre = article.quantite entre -= vente.quantite_v if entre >= 0: article = vente.id_article article.quantite -= vente.quantite_v print('article final :', article.quantite) totalvente +=article.prix_de_vente * vente.quantite_v print('Total à payer :',totalvente) article.save() print('article sauve',article.quantite) else: vente.delete() messages.warning(request, 'Stock insuffisant pour cette opération! ') return render(request, self.template_name, {'form': self.VenteFormSet(),'totalvente':totalvente}) else: messages.warning(request,'Formulaire invalide!!!') return render(request, self.template_name, {'form': self.VenteFormSet(),'totalvente':totalvente}) #except: # vente.delete() # messages.warning(request, 'Recommencer une nouvelle fois, présence !!!') #return render(request, self.template_name, {'form': self.VenteFormSet(),'totalvente': totalvente}) -
Set template and wrapper_class parameters and render single form field not form
Related Q&A. You can consider this question follow up of it My form class is: class RoomForm(ModelForm): room_in_type = forms.ChoiceField(choices = [(elem[0], elem[1]) for elem in filter(lambda x: x[2] == False, memcache.Client().get("room_in_type_choices"))], widget=forms.RadioSelect()) class Meta: model = Room def __init__(self, *args, **kwargs): super(RoomForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_action = form_action self.helper.label_class = 'col-md-8' self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( InlineRadios('room_in_type', required=True, css_classes="col-md-8", template='some_template.html'), Field('country', required=True, css_class="country-container", wrapper_class ='toto-class'), Field('fb_user', type='hidden') ) relevant part of my template is: {{ form.country | as_crispy_field}} {{ form.room_in_type | as_crispy_field}} in this case: neither template='some_template.html' nor wrapper_class ='toto-class' is considered but if I render {% crispy form%} both field take place. My question is: Isn't it possible, to give those parameters while rendering as single field? -
django Date time input
I need that in my castration form in the part of chckin and checkout it appears a calendar with date and time, so that the usurario does not have to type manually, I tried using widgets, but the input of the form appears like normal input. And I need the calencario with day, month, year and hour and minute models.py from django.db import models import math class MovRotativo(models.Model): checkin = models.DateTimeField(auto_now=False, blank=False, null=False,) checkout = models.DateTimeField(auto_now=False, null=True, blank=True) valor_hora = models.DecimalField( max_digits=5, decimal_places=2, null=False, blank=False) veiculo = models.ForeignKey( Veiculo, on_delete=models.CASCADE, null=False, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) forms.py from django.forms import ModelForm from django import forms class DateTimeInput(forms.DateTimeInput): input_type = 'datetime' class MovRotativoForm(forms.ModelForm): class Meta: model = MovRotativo fields = '__all__' widgets = { 'checkin': DateTimeInput(), 'checkout': DateTimeInput(), } -
Exclude nested model field in django serializer
So I have two django models but one of them has a field I need to exclude called code. I haven't found a way to exclude this field using the serializer class. class ModelA(models.Model): modelBs = models.ManyToManyField('ModelB') class ModelB(models.Model): # assume all sorts of fields here like name, location, etc.. code = models.CharField(max_length=200) My issue is I can't exclude the modelB code when serializing model A like so: class ModelASerializer(serializers.ModelSerializer): class Meta: model = ModelA exclude = ('modelBs__code') The serializer above does not work. Anyone know how to go about this? -
Django admin current file path
I can upload files in a section in admin panel. in models.py file = models.FileField(verbose_name="Upload",upload_to='static/teaching/') when I want to see this file it goes like this; http://127.0.0.1:8000/admin/teaching/teaching/1/change/static/teaching/Ads%C4%B1z.png I want it to go like this; http://127.0.0.1:8000/static/teaching/Ads%C4%B1z.png how can I fix this? enter image description here -
How to write raw query in ElasticSearch Django?
I was trying to implement elastic search in Django where I try to use raw query to find data. Now How could I write a raw query? Here is my Code. def searchPage(request): q = request.GET.get('q') if q: # here I try use raw but I'm Getting Error that 'Search' object has no attribute 'raw' titleInfo = GetItem.search().raw("select * from item WHERE title LIKE % %s %", [q]) else: titleInfo = '' return render(request, 'searchPage.html', {'titleInfo': titleInfo}) -
Taking site screenshot whit python and django or javascript
i want create feedback plugin by python-django, in this app user should take screenshot of problem and edit it, which best way for write this plugin? i am using canvas model but in Persian language some part is don't show correct -
Django modify object only during comparsion in custom Lookup Field
I have models like these: class Product(models.Model): id = models.IntegerField(null=False) name = models.TextField(null=False) quantity = models.IntegerField(default=None) price = models.IntegerField(default=None) bar_code = models.ForeignKey(Manufacturer, related_name='manufacturers') class Manufacturer(models.Model): name = models.TextField(null=False) country_of_origin = models.TextField(null=True) local_naming = models.Textfield(null=False) At the beginning, field Manufacturer.local_naming looked like AAA001, AAA002 and so on and this gave me easy way to query less or equal local_naming, because Python handles string comparison very well and Product.objects.filter(manufacturers__local_naming__lte='AAA003) would get me objects with AAA001 and AAA002 as value in relation with class field Manufacturer.local_naming. But naming convenction has changed reciently and I want to preserve custom order - new names contain current year prefix so it looks like this - 18AAA001and Python can't keep my custom order, because '18AAA001' > 'AAA01' returns False, when I wanted True. So I came up with idea to add prefix before those three letters in the name if there's none, so name AAA001 would change to 00AAA001, but what's important, I do not want to modify existing values in any way and because of that I was thinking about creating custom lookup and change the values only for the time of lookup. I wrote this code @Field.register_lookup class LocalNamingLessThanEqual(Lookup): lookup_name = 'ln_lte' def as_sql(self, compiler, … -
Calcul Time on django
I have the following code: def index(request): events_list = Timesheet.objects.filter(owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1]).order_by('-working_hour') total_hours_week = Timesheet.objects.annotate(total_hours_per_week=Sum('working_hour')).filter(owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1]) return render(request, "timesheet/index.html", {'events_list': events_list, 'total_hours_week': total_hours_week}) the total_hours_week retun the current error: You cannot use Sum, Avg, StdDev, and Variance aggregations on date/time fields in sqlite3 since date/time is saved as text. Do you know how to fix ? thanks per advance -
Why is JavaScript replace not working in Django?
I have some code that takes an HTML template and replaces all {{tags}} with their appropriate values. The code works everywhere else in its raw form (without Django). Here's a jsFiddle for proof. However, it does not work in PyCharm when I put it inside my Django project. HTML <h1>Infinite Scroll - Loading JSON</h1> <p>Loading photos from the <a href="https://unsplash.com/developers?utm_source=infinite-scroll-demos&utm_medium=referral&utm_campaign=api-credit">Unsplash API</a></p> <div class="container"></div> <div class="page-load-status"> <div class="loader-ellips infinite-scroll-request"> <span class="loader-ellips__dot"></span> <span class="loader-ellips__dot"></span> <span class="loader-ellips__dot"></span> <span class="loader-ellips__dot"></span> </div> <p class="infinite-scroll-last">End of content</p> <p class="infinite-scroll-error">No more pages to load</p> </div> <!-- .photo-item template HTML --> <script type="text/html" id="photo-item-template"> <div class="photo-item"> <img class="photo-item__image" src="{{urls.regular}}" alt="Photo by {{user.name}}" /> <p class="photo-item__caption"> <a href="{{user.links.html}}?utm_source=infinite-scroll-demos&utm_medium=referral&utm_campaign=api-credit">{{user.name}}</a> </p> </div> </script> <script src="https://unpkg.com/infinite-scroll@3/dist/infinite-scroll.pkgd.min.js"></script> JavaScript // Get an API key for your demos at https://unsplash.com/developers var unsplashID = '9ad80b14098bcead9c7de952435e937cc3723ae61084ba8e729adb642daf0251'; var $container = $( '.container').infiniteScroll({ path: function() { console.log(this.pageIndex); return 'https://api.unsplash.com/photos?client_id=' + unsplashID + '&page=' + this.pageIndex; }, // load response as flat text responseType: 'text', status: '.scroll-status', history: false, }); $container.on( 'load.infiniteScroll', function( event, response ) { // parse response into JSON data var data = JSON.parse( response ); // compile data into HTML var itemsHTML = data.map( getItemHTML ).join(''); // convert HTML string into elements var $items = $( … -
how to add python code in href attribute in html tag
I am new to python, I have a code that iterates the list in HTML using python {% for e in news %} <h5 class="title"> {{ e.title }}</h5> <a href="{% e.url %}"> url </a> {% endfor %} getting template syntax error in href tag. Please let me know if you know the solution. -
uwsgi ini file does not create a sock file
I am trying to configure nginx to work with my django project. I create my ini file called myfoo.ini right above the folder that contains settings.py. This is the content of that file [uwsgi] module = main.wsgi:application master = true pidfile = django.uwsgi.pid enable-threads = true http = 127.0.0.1:8000 processes = 5 socket = /home/ec2-user/MyVenv/MyWeb/foo.sock harakiri = 50 max-requests = 5000 vacuum = true home = venv daemonize = django.uwsgi.log ; If VIRTAL_ENV is set then use its value to specify the virtualenv directory if-env = VIRTUAL_ENV virtualenv = %(_) endif = Any suggestions on why the sock file is not being created ? This file is next to my other django apps ? I was expecting that once I do this uwsgi --ini my_foo.ini It should create a .sock file next to it. However that is not happening any idea if I am doing something wrong ? Also is it ok to place my_foo.ini next to other apps ? -
Django user registration and login using Djnago-Phone-Login
I installed django-phone-login using pip install django-phone-login I followed the instructions given for configuring setting.py file. When i ran server after configuring settings, i saw error as given below. ERRORS: : (admin.E108) The value of 'list_display[0]' refers to 'phone_number', which is not a callable, an attribute of 'PhoneTokenAdmin', or an attribute or method on 'phone_login.PhoneToken'. I have can there were multiple similar question asked for the same error. Django-phone-login Django Registration with phone To me it's sound like there is no work going on this project. So I am wondering if Django-Phone-Login worth considering for new project to implement registration and login process If it's good to consider and production ready app then how to sort out this error in my project. Your advise is highly appreciated on this. -
creating a file when a user signup
I need a file to be created at the time when a user sign up below is my signup view.py in django: class SignUp(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' what should i do , so that a file will be created at the time when user signup -
Can one table has more than one primary key in Django?
I have following table structure. When I try to migrate, I got following error. django.db.utils.OperationalError: table "certificate_light" has more than one primary key However, I found other stack overflow page saying that one table can have more than one primary key in RDBMS. Can anyone know how I can implement table having more than one primary key in Django? models.py class Certificate(models.Model): name=models.CharField(max_length=20) class Zone(models.Model): zone=models.CharField(max_length=20) conditioned=models.BooleanField(default=True) class Light(models.Model): certificate=models.ForeignKey(Certificate, on_delete=models.CASCADE,related_name='certificate') zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='lightzone') lpd=models.IntegerField() sensor=models.BooleanField(default=True) -
managing django websites with many pages
I am creating my first web application and I wanted this website to have so many pages in the future. But the problem is that I need to manage those pages easily. something like wordpress and I have no idea how to manage a website with like thousands of pages Any tips? -
Uploading large raster geodjango
I created a geodjango model using RasterField(). I have been trying to upload the raster using postgis. I load the raster like so raster = GDALRaster('rasters/data/my_image.tif', write=True) r = Rast(name="Hello", image=raster) r.save() Everything works fine until I try to save the object and get django.db.utils.OperationalError: cannot allocate memory for output buffer. I am not sure how to solve this. The raster is a single image that is around one gb. When I look at my usage during this process I notice that alomst all of my 32gb of ram is being used for some reason. Can this be chunked? Or is there an alternative to saving this. -
Empty form with MultiChoiceField raising NoReverseMatch error in django
model class MyModel(models.Model): user_account = models.OneToOneField(User, on_delete=models.CASCADE) remark = models.CharField(max_length=120) data_1 = models.BooleanField(default=False) data_2 = models.BooleanField(default=False) data_3 = models.BooleanField(default=False) data_4 = models.BooleanField(default=False) form class MyModelForm(forms.ModelForm): CHOICES= (("data_1", "data_1"), ("data_2", "data_2"), ("data_3", "data_3"), ("data_4", "data_4"),) my_choice = forms.MultipleChoiceField(choices=CHOICES, widget=forms.CheckboxSelectMultiple()) class Meta: model = MyModel fields = ["remark"] views class MyView(UpdateView): model = MyModel form_class = MyModelForm template_name = "mytemplate.html" def form_valid(self, form): selected_choices = self.request.POST.getlist("my_choice") for item in selected_choices: setattr(form.instance, choice, False) form.instance.remarks = form.cleaned_data["remark"] form.instance.save() return super(MyView, self).form_valid(form) def get_success_url(self): return reverse("app:detail-update-url") form works perfectly fine when i submit the form with data.But it raises Noreversematch with keyword arguments '{u'pk': ''}' not found. 1 pattern(s) tried when i try to submit the form without checking any of the checkbox.The remark field have required =True so it works fine.what i want is, i need to display the error when non of the checkbox checked any help will be appreciated.. :)