Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Append in for loop Django python
I need to use like query in array Views.py keywords_array=[] for i in keyword: keywords={} if keyword[0]==i: keywords="rk.keywords LIKE '%%"+i+"%%'" else: keywords="OR rk.keywords LIKE '%%"+i+"%%'" keywords_array.append(keywords) for t in keywords_array: raw_query="SELECT r.id,( 3959 * Acos(Cos(Radians(" +lat +")) * Cos(Radians(lat)) * Cos( Radians(lng) - Radians("+lng+")) + Sin (Radians("+lat+")) * Sin(Radians(lat)))) AS distance FROM backend_restaurant r LEFT JOIN backend_restaurant_keywords m2m ON m2m.restaurant_id = r.id LEFT JOIN backend_restaurantkeyword rk ON m2m.id = rk.id WHERE "+ t +"" print(raw_query) keywords_array: ["rk.keywords LIKE '%%Donut%%'", "OR rk.keywords LIKE '%%Pizza%%'"] I need to append this in raw_query but it is being returning single array : SELECT r.id,( 3959 * Acos(Cos(Radians(30.704649)) * Cos(Radians(lat)) * Cos( Radians(lng) - Radians(76.717873)) + Sin (Radians(30.704649)) * Sin(Radians(lat)))) AS distance FROM backend_restaurant r LEFT JOIN backend_restaurant_keywords m2m ON m2m.restaurant_id = r.id LEFT JOIN backend_restaurantkeyword rk ON m2m.id = rk.id WHERE OR rk.keywords LIKE '%%Pizza%%' -
Insert Placeholder through CSS
<div class="col-sm-2"> {{ adminform.form.writer }} </div> In the above code there is no input html tag how to insert placeholder named 'writer' ? -
Appending a value (to a list) to a key in a JS object and sending AJAX request with said object to Django
So I know it seems like part of this answer is everywhere, but it took me forever to even get as far as I am now, and that was piecing about 50 different SO answers together, so please bear with me. Basically, for the past 2 days I've been trying to figure out how to pass a JS dictionary from the client-side to my Django views.py so I can access the keys and associated values, ultimately using them to query my database to render a view using Django template tags. I finally got it where I can append multiple values successfully to an object cart_dict client-side. However, when I try to send the AJAX request through to Django and print out the results, extra square brackets are appended after the keys and I'm not sure why. More importantly, I don't know how to fix this, and can only think that my only option is to write a script to remove them. I'm hoping I can avoid that though, and there is something I'm simply missing. I have a feeling it might have something to do with me instantiating a new array to append all duplicate values for an associated key, … -
Why doesn't Django-simple-math-captcha render question?
I'm trying to integrate Django-simple-math-captcha in my project, but the form doesn't render the question. I've followed all the steps in the docs, and render the form: {% for field in form %} {{ field.label_tag }} {{ field }} {% if field.errors %} {{ field.errors }} {% else %} {% endif %} {% endfor %} I get the captcha label i.e. Captcha: and the captcha answer input, but no question. What have I done wrong? -
Django: object attribute showing different values
So this looks like a lot of code, but I only really care about the two lines where I put arrows. This code snippet is from a template (html) file. solutions_newest is an array full of "solution" objects. A "solution" has an attribute called "id". {{ solution.id }} accesses the id of a solution. The two lines where I put arrows are in the same for loop, so it should be accessing the same solution at a given time. However, when I display {{ solution.id }} in both these lines, the first line displays the id of the selected puzzle, and the second line always displays the id of the first puzzle of the "solutions" array. How can this be? I suspect that I am not fully understanding how Bootstrap modals work, but to be honest I have no idea why {{ solution.id }} is showing different ids in the two lines with arrows. {% for solution in solutions_newest %} <div class="card bg-light"> <div class="card-header subtitle"> <div class="triple-left">{{ solution.datetime }} by <a href="{% url 'profile' username=solution.user.username %}">{{ solution.user.username }}</a> </div> {% if user == solution.user or user.profile.teacher %} <div class="triple-right"> <a href="{% url 'edit_solution' puzzleID=solution.puzzle.id solutionID=solution.id %}">edit</a> &nbsp;&nbsp; --------------> <a … -
Django get object info to method without re-entering it
I'm not exactly sure how to explain it. I am trying to use "custom save method" sort of. At any rate, hopefully my code makes sense. I am currently testing a CustomUser model. I want to generate a username if none is given. I am also using the full_clean method as to not save instances that are blank. Here's what I have: test # Don't get hung up on the way I create the user. I have a reason for this. user = { 'username': '', 'password': 'testpassword', 'first_name': 'Testy', 'middle_name': 'Tester', 'last_name': 'Testman', 'email': 'testman@test.com', } def test_CustomUser_will_generate_username_if_none_provided(self): CustomUser(**user).full_clean_save() model method: def full_clean_save(self): # How do I get my 'username' reckognized here if it isn't ''? # This always is == '' if self.username == '': # Makes a random username from BaseUserManager self.username = CustomUser.objects.make_random_password() self.full_clean() self.save() -
How to store Model methods separately?
I have an AbstractUser model which adds about 20 custom model methods. I want to store these methods properly and idea is to sort it by logic, for example AdminMethods, PaidUserMethods etc. I tried to use models.Manager but it dont let me get user instance via self. How can I store that methods properly? Thanks! -
Why the select for update not working in django mysql?
I have a table like below select id, name from node; +----+------+ | id | name | +----+------+ | 5 | na | +----+------+ Then define below function def foo(seconds, value): with transaction.atomic(): node = Node.objects.select_for_update().filter(pk=5) time.sleep(seconds) update_result = Node.objects.filter(pk=5).update(name=value) return update_result The function should lock row pk=5 and update it with value. During the transaction the function will sleep several seconds so It will give me time to test the lock in another console. First run the function in one console update_n1_without_sfu(10, 'value1') Then I run update in another console with sql command update node set name='nb' where id=5; I was expecting the second console being blocked because the first console should lock the row with select for update. But the second row did not get blocked. So why? -
ManyToManyField field do not display in the admin page when add records
I want to create many-to-many relationship with these 2 tables 1.Qa table ------------- |ID | QA | ------------- |1 |qa1 | |2 |qa2 | |3 |qa3 | ------------- 2.Tag table ------------- |ID | Tag | ------------- |1 |tag1 | |2 |tag2 | |3 |tag3 | ------------- for that I made a 3 models like below Qa model class Qa(models.Model): question_text = models.CharField(max_length=1000, verbose_name='Question') tags = select2.fields.ManyToManyField(Tag, blank=True, through = 'Qa_Tag', verbose_name='Tag') """ And some more fields. """ def __str__(self): return self.question_text class Meta: ordering = ("id",) verbose_name = 'QA data' Tag model class Tag(models.Model): tag_text = models.CharField(max_length=30, unique=True, verbose_name='Tag') def __str__(self): return self.tag_text class Meta: verbose_name = 'Tag' and a model for keep relationship Qa_Tag model class Qa_Tag(models.Model): tag = models.ForeignKey(Tag, verbose_name='tag') qa = models.ForeignKey(Qa, verbose_name='qa') def __str__(self): return self.tag.tag_text and in my forms.py I add these fields. class QaAdminForm(ModelForm): class Meta: model = Qa fields = ('question_text', 'tags', 'some_more-fields') When I try to add a QA record the form, shows every field except tags. If I register this models in admin.py I could add data to Tags and QA and then I can make the relationship via Qa_tag. But actually I don't want that Qa_tag. without through = 'Qa_Tag' … -
In django + mysql, why do we need select for update since there is atomic (transaction)?
I want to know the scenarios where 'SELECT FOR UPDATE' is necessary and can not be replaced by the atomic -
Django Modelmultiplechoicefield Checkboxselectmultiple Problem Getting Selected Checkbox
I have been working all day to try and get the selected values on one set of checkboxes on my Django form and copy the selected ones only to an identical checkbox on my form. If a user clicks on a checkbox in form.author defined below, I want the same identical checkbox to automatically be checked on form.favorite_author defined below. I've tried a JQuery approach as documented here...Copy Selected Checkbox Value From One Checkbox To Another Immediately Using JQUERY but no luck so far. I've recently begun exploring an avenue with the Modelmultiplechoicefield and the checkboxselectmultiple parameters within the form itself. From what I can tell, when I am using JQuery and trying to check a box on the form, the value is coming back as undefined which is most likely why it is not propagating the checkbox selection to the other checkbox. Here is my form.... class ManagerUpdateNewAssociateForm(forms.ModelForm): class Meta: model = Library self.fields['author'] = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple(), queryset=Books.objects.all() self.fields['favorite_author'] = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple(), queryset=Books.objects.all() My HTML... <div class="spacer83"> {{ form.author }} </div> <div class="spacer83"> {{ form.favorite_author }} </div> When I tried to trace JQuery, it told me the checkbox selections are undefined. I did read a bit about how Modelmultiplechoicefield, … -
Passing a Python object from views to template django
I'm trying to pass an object from views.py to a template.html file. But here is the catch: The object is not a model, it's a python object. Here is an example: class Day: date = 0 views = 0 bounces = 0 def __init__(self, day, views, bounces): self.day = date self.views = views self.bounces = bounces def house_view(request): week_data = api.get_weeks_data() days = [] for day_data in week_data: day = Day(day_data.date, day_data.views, day_data.bounces) days.append(day) return render(request, 'nalytics.html', {"days": days}) It seems none of these days or their data can be accessed in the view using {{}} or {%%}. Does this mean I need to make a model? Anything helps, thanks for your time! -
Variables not updating from an imported variable in Django?
Today I have ran across an interesting roadblock in my Django program. I am trying to create a small calendar program where users can see a calendar in a textarea, and update it with whatever they want and it will push the update to the calendar and you will be able to see the updated calendar from anywhere. I tried using a file to store the calendar information, but that ran into problems with the file not updating and whatnot. So instead, I have taken a new approach by instead storing the calendar in a global variable and passing the information around to wherever in the program it is needed. Here is the program: views.py from django.shortcuts import render from django.contrib import messages import sys global file_content f = open('calendar.txt', "r") file_content = f.read() f.close() if f.closed: print("CLOSED FILE from read views") def writeFile(content, file): from .forms import FileForm f = open(file, "w") f.write(content) f.close() if f.closed: print("CLOSED FILE from write views") def home(request): from .forms import FileForm return render(request, 'main/index.html',{'file_content':file_content}) def form_get(request): from .forms import FileForm if request.method == 'POST': # create a form instance and populate it with data from the request: form = FileForm(request.POST) # check whether … -
Django "add" Template Tag when variable may be empty
I am wondering if it is possible to use django's add tag to add two queryset objects, when one may or may not be empty depending on the instance. I have seven different queryset totals that I want to total up, and some may be empty at different times. Is there an easy way to do this or do I need to write a long if statement or do it in the view? -
update value using Custom Action Buttons (not actions) to Django Admin list page?
I have following change form in templates\admin\pages\Device Which creates add a button "Make Immortal" {% extends "admin/change_form.html" %} {% load i18n %} {% block object-tools-items %} <div > <form action="." method="POST"> {% csrf_token %} <button type="submit">Make Immortal</button> </form> </div> <br /> <br /> {{ block.super }} {% endblock %} My admin page looks like this: #app/admin.py class DeviceAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() my_urls = [path('device/', self.set_immortal), path('device/', self.set_mortal), ] return my_urls + urls def set_immortal(self, request): self.model.objects.all().update(power=True) self.message_user(request, "All devices are up") return HttpResponseRedirect("../") def set_mortal(self, request): self.model.objects.all().update(power=False) self.message_user(request, "All devices are off") return HttpResponseRedirect("../") When I click on Make mortal it opens a empty device form like below. All i want is update the power state in the database and show the message. Then shows the updated value in the change form. I am following below tutorials but was not able to fix the problem https://media.readthedocs.org/pdf/django-admin-cookbook/latest/django-admin-cookbook.pdf#page=21&zoom=100,0,424 -
Django forms with two different models
I'm making a questionnaire app, where the question model/table has a variable number of questions, but the response format is uniform e.g. between 1-5. They are contructed like this: class Question(models.Model): sid = models.ForeignKey(Survey, on_delete=models.CASCADE) question_title = models.TextField() def __str__(self): return self.question_title class Response(models.Model): quid = models.ForeignKey(Question, on_delete=models.CASCADE) response = models.CharField(max_length=2) def __str__(self): return self.response I'm really confused at modelForms. My desired end result is a form with a label and standardized input for each Question, but the data would pass to the Response model. A bit confused about how to approach this. I don't want to hard-code a template with questions in case more questions are added, names changed etc. How does one approach this? -
Retrieve user Object from Username
I have a need to get the is_staff value from a given user inside a forms.py, to only create certain form fields if is matches the permissions. I'm currently using django-currentuser which I'm able to get the username of the current logged in user. Now in order to check for is_staff, I would need to get the whole User object. Found several places, and all say to do the following: from django.contrib.auth.models import User user = User.objects.get(username='<username>') if user.is_staff: do_stuff() Running this from the manage.py shell seems to be working. But trying to implement the same inside forms.py does not return anything. As a note here to say I'm not using a views.py. The whole form is driven by crispy_forms, and output content inside a template file. As I have found different solutions on how to get the user object from requests Any idea how I could get the user object, or the is_staff value of the user inside forms.py? -
Django Trailing Slash throws 404
I have a django application with DRF and didn't change default APPEND_SLASH. Here is my url conf: router = DefaultRouter() router.register(r'', SampleViewSet, 'sample') urlpatterns = [ url(r'^sample/', include(router.urls)) ] So when I call the api from Browser as below, api/v1/sample/1 it redirects the request with 304 to the api/v1/sample/1/ which throws 404. I have the resource in db for sure. Not sure where my mistake is. I would really appreciate any help. -
How to use multiple annotation with filter in Django?
I have use below code for getting result but always get same output for total_deal and total_coupons. I dont know what is happening in this code. total_coupons = Count('coupon', filter=Q(coupon__is_sale__lte=0)) total_deals = Count('coupon', filter=Q(coupon__is_sale__gt=0)) queryset = coupon.objects.values('store_id','store_name','store_site','affiliate_url').annotate(total_deals=total_deals, total_coupons=total_coupons) -
Translate SELECT WHERE MAX query to django
Me and a few friends have been banging our head against this for a while, but to no avail. We have this SQL query: SELECT * FROM mappings m, ( SELECT output_id, MAX(created) AS created FROM mappings GROUP BY output_id ) t WHERE m.output_id = t.output_id AND m.created = t.created; Essentially, we are retrieving the most recent Mapping for each output_id. Now... that works. How do we put it into Django? We have boiled the inner query to the following... but dont know where to go from there Inner query: inner_qs = Mappings.values('output_id').annotate(Max('created')).order_by() But, no clue how to integrate that into the outer query. Any ideas? Thanks!! -
Django 2: unresolved attribute reference 'get_queryset' for class
get_queryset is not work in model manager models.py model manager class ProductManager(models.Model): def featured(self): return self.get_queryset().filter(featured=True) I'm trying to solve this problem using supper class. But isn't work return super(ProductManager, self).get_queryset().filter(featured=True) model class Product(models.Model): title = models.CharField(max_length=120) price = models.DecimalField(max_digits=20, decimal_places=2) description = models.TextField(null=True, blank=True) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) featured = models.BooleanField(default=False) objects = ProductManager() Error AttributeError: 'Manager' object has no attribute 'featured' views.py class ProductListFeaturedView(ListView): # model = Product template_name = 'products/list.html' def get_queryset(self): return Product.objects.featured() first time i'm facing this problem. -
Django with application
This is a noob question. I post this here because I'm so lost that after hours and days of googling I realized I even don't know what to look for. I'm a C++ developper and have a developped C++ app. On the other hand, I recently dug into web development and created a website using the Django framework, which I host on Heroku. The flow of the website: a user enters input on the website, input files are uploaded to AWS S3 (I managed to get that working). The part I'm lost: with the user input, I'd like to run the C++ app which I host on a linux server (Codenvy). But I have no idea how to launch that application from the django site which is served by Heroku. Can someone help me out here? At least giving some keywords to enhance my google searches? Thanks a lot! -
How do I correctly pass multiple arguments (from the template/context) to a view in Django?
I am relatively new to Django (v=2.1). I am stuck since few days searching for a solution to this problem which I think is fairly easy but, despite reading many posts here and elsewhere, did not manage to solve it yet. I have two models: Teacher and Assignment. Very simplified: models.py class Teacher(models.Model): name = models.CharField(max_length=200) class Assignment(models.Model): title = models.CharField(max_length=200) teacher = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True) I have a (working) site with a list of Assignments of teacher nr. x which I produced with a generic DetailView function and some of the code looks like this: assignments_list.html {% for assignment in teacher.assignment_set.all %} ... <a href="{% url 'assignment-detail' pk1=assignment.teacher.pk pk2=assignment.pk %}">{{assignment.title}}</a> ... {% endfor %} When I click on the assignment.title I want to get the detail page of the assignment of this specific teacher. I use this url conf: urls.py urlpatterns += [path('teacher/<int:pk1>/assignment/<int:pk2>/', views.AssignmentDetailView.as_view(), name = 'assignment-detail')] and I use this view function (I tried several variants): views.py from .models import Teacher, Assignment from django.views import generic class AssignmentDetailView(generic.DetailView): model = Assignment template_name = 'assignment_detail.html' def get_queryset(self, **kwargs): queryset = super(AssignmentDetailView, self).get_queryset() return queryset.filter(teacher_id=self.kwargs['pk1'], pk=self.kwargs['pk2']) I'm trying to pass the two parameters (pk1 and pk2) that are in the … -
Django Form for voting
I have a web form that has two fields named gender and diseases. I want to create a vote submit button that takes classifies how many males and females have HIV,CHOLERA(diseases field) etc. How do I go about this.I am new to django. Views.py from django.views.generic import ListView, CreateView, UpdateView from django.urls import reverse_lazy from . models import MyModel from . forms import MyModelForm class CreateMyModelView(CreateView): model = MyModel form_class = MyModelForm template_name = 'poll/template.html' urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.CreateMyModelView.as_view(), name='abc') ] models.py from django.db import models Gender = ( ('male', 'MALE'), ('female', 'FEMALE'), ) Diseases = ( ('cholera', 'CHOLERA'), ('hiv', 'HIV'), ('Malaria', 'MALARIA'), ('Typhoid', 'TYPHOID'), ) class MyModel(models.Model): Gender = models.CharField(max_length=16, choices=Gender, default='MALE') Diseases = models.CharField(max_length=16, choices=Diseases, default='MALARIA') forms.py from .models import MyModel from django import forms class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['Gender', 'Diseases'] template.html {% extends 'poll/base.html' %} {% block main_content %} <h1></h1> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Vote" /> </form> {% endblock %} -
Paypal not accessing IPN notify URL
I'm trying to get Paypal to send IPN messages after purchases on my site but it's not accessing my IPN notify URL. I'm using Python and Django and I've been having problems with the Paypal sandbox so I've just been using two Paypal accounts with the same bank account and returning the money each time. I've set up a button on the Paypal site and put my notify URL in there and also in the general IPN settings. In my Django views file I've set up the function for the notify URL to email me when it's accessed but it's not doing it when I send a payment. I read that it might be because I don't have a SHA-256 certificate, but I checked on the Qualys server checker and I do have one. Does anyone have any idea what I'm doing wrong?