Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django EmailMessage replay_to object not passing through to headers
So, I've tried every possible combination and cannot get the reply_to object to pass to the headers; even if I hard-code the reply_to email address. The form works other than that without any issues. Thank you for your help versions Django==1.10.1 sendgrid==3.6.3 sendgrid-django==4.0.4 view def index(request): form_class = FooterForm if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): fullname = request.POST.get('fullname') phone_number = request.POST.get('phone_number') email_address = request.POST.get('email_address') message_content = request.POST.get('message_content') subject = 'Contact Information Submitted from Trust and Beneficiary Advocates' from_email = settings.DEFAULT_FROM_EMAIL recipient_list = 'info@trustadvocates.com' bcc = 'charles@studiorooster.com' ctx = { 'title': 'Trust and Beneficiary Advocates', 'subject': subject, 'fullname': fullname, 'phone_number': phone_number, 'email_address': email_address, 'message_content': message_content } message = get_template('email_forms/contact_form_email.html').render(Context(ctx)) msg = EmailMessage( subject, message, from_email, [recipient_list], [bcc], reply_to=['helpme@helpme.com'] ) msg.content_subtype = 'html' msg.send() return redirect('/thank-you/') return render(request, 'pages/index.html', { 'form': form_class, 'title': 'Trust and Beneficiary Advocates' }) reply_to combinations tried reply_to=['helpme@helpme.com'] headers={'Reply-To': 'helpme@helpme.com'} -
Different Django CMS menus for different django apps
Maybe I'm just blind, but I couldn't really find anything that would help me solve this problem. I've got a Django project where I'm using Django CMS, for example to display a menu on all sites. Now I want to add an additional Django sub-app, which should display a completely different menu. Is there any preferred way to do this? For now I arrived at following solution. I'm using two cms_menus.py, one that defines the NavigationNodes used for all hitherto sites and one that defines the NavigationNodes for the new sub-app. So each NavigationNode has a namespace (out of the box), that basically indicates where it should be displayed. And I got a Modifier that removes all NavigationNodes that have a differing namespace if it is set: class NamespaceModifier(Modifier): def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb): if post_cut: return nodes if namespace is not None: # only return nodes from given namespace return [node for node in nodes if node.namespace == namespace] return nodes menu_pool.register_modifier(NamespaceModifier) The motivation for this is, that the show_menu template tag accepts the namespace paramter, as specified in the docs: "The fifth parameter, namespace specifies the namespace of the menu. if [sic] empty will use … -
function in jquery does not work after it get redirected
I am trying to run a function(that shows a flash message) in a jquery function after I do the window.location.href to redirect to a new page but it does not work. Even the console.log("confirmnewpage") does not show up at the new page. I have already tested to confirm that the function showFlashMessage(msg) works, it just doesn't work inside the click function. Is there any way to do it so the flashmessage or any other function could run after it gets redirected to a new page? By the way I am using django as my backend if that matters. Thanks My html <form class='db' action='{% url 'Contact' %}' msg='Hello John!' method="post" style="display: inline">{% csrf_token %} <input class='btn btn-success buttonspace' type="submit" value="Home"> </form> my javascript <script> $(document).ready(function(){ {% block jquery %} function showFlashMessage(message) { var template = "<div class='container container-alert-flash'>" + "<div class='col-sm-10 col-sm-offset-1'> " + "<div class='alert alert-success alert-dismissible' role='alert'>" + "<button type='button' class='close' data-dismiss='alert' aria-label='Close'>" + "<span aria-hidden='true'>&times;</span></button>" + message + "</div></div></div>" $("body").append(template); $(".container-alert-flash").fadeIn(500); setTimeout(function(){ $(".container-alert-flash").fadeOut(500); }, 5000); } $(".db").click(function(e){ e.preventDefault() var Url = $(this).attr("action"); var msg = $(this).attr("msg"); $("#dc").fadeIn("300") $("#dc").dialog({ resizable: false, height: 200, width: 350, modal: true, show: { effect: 'fade' }, hide: { effect: 'fade' }, buttons:{ … -
Process Views outside viewflow.frontend
I want to integrate processes, starting them etc., outside of the standard viewflow.frontend. To do I have been trying to create a simple page where I can start a new process, but have been struggling to find a way to implement it. One approach was to defined a url to url('^start_something, CustomStartView.as_view()) with CustomStartView subclassing CreateProcessView from viewflow.flow.views.start. This ended in getting error after error, whenever I fixed one. I am quite sure now that this isn't the right way to do it, also because the View is used as a parameter of the Flow class itself and probably needs to be used differently than a common view. What is the right way to do it? -
OWASP ZAP configuration with django Admin login
The problem I can't configure my OWASP ZAP application to log in and Scan the pages which require authentication. My page is the built in Django admin page. I've recorded a script following the instruction from this page: https://www.coveros.com/scripting-authenticated-login-within-zap-vulnerability-scanner/ The script can log in. I've set it as Script-based Authentication Login URL : http://127.0.0.1:8000/admin/ Method: POST Logged in indicator regexp: \Qlogout\E Logged Out indicator regexp: \Q/admin/\E I'm not sure if it is a must to add the user, but I've added it. Session Management: Cookie Based (tried it with HTTP based as well ) When I click on Attack Scan/Spider, the scanned pages are only which do not require authentification. Eg.: The /admin/logout/ page is not discovered Please let me know what am I doing wrong? Thanks -
Django allow the user to edit their profile
views.py class ProfileEdit(LoginRequiredMixin, UpdateView): login_url = '/login/' model = User slug_field = "username" fields = ['full_name'] template_name="profile/profile_new.html" models.py class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'),max_length=120, unique=True, blank=False) email = models.EmailField(_('email address'), unique=True) full_name = models.CharField(_('full name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(_('staff'), default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] I want to allow only the user to edit the profile only if he is the logged in user. what is the best approach to this question? UserPassesTestMixin or user_passes_test()? -
how to access data from database in python using javascript
I am working with a python django project.I have no idea how to access database values in python using java script.I have a table employees in my db.and I want to access all the data from this table using the select query.select * from employees. And my java script is <script> $(document).ready(function() { $("#id_record").change(function(){ var recording=$("#id_record option:selected").text(); //here I want to access the `employees` table details.and how i can access that here? }); }); </script> please help me,thanks in advance -
.capitalize() and .upper() Django form fields
I'm asking a question about Django form fields and How I could handle data. I have a models.py file with some CharFields. User filled form like this : Lastname : einstein Firstname : albert birthcity : ulm But I want that my script automatically returns in my database data like : Lastname : EINSTEIN Firstname : Albert Birthcity : ULM So, I want to set UPPER both fields : lastname and birthcity and set Capitalize firstname field`. I wrote this : class BirthCertificate(models.Model): lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille') firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)') sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe') birthday = models.DateField(null=False, verbose_name='Date de naissance') birthhour = models.TimeField(null=True, verbose_name='Heure de naissance') birthcity = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance') birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance') fk_parent1 = models.ForeignKey(Identity, related_name='ID_Parent1', verbose_name='ID parent1', null=False) fk_parent2 = models.ForeignKey(Identity, related_name='ID_Parent2', verbose_name='ID parent2', null=False) created = models.DateTimeField(auto_now_add=True) def save_upper(self, *args, **kwargs): for field_name in ['lastname', 'birthcity']: val = getattr(self, field_name, False) if val: setattr(self, field_name, val.upper()) super(BirthCertificate, self).save(*args, **kwargs) def save_capitalize(self, *args, **kwargs): for field_name in ['firstname']: val = getattr(self, field_name, False) if val: setattr(self, field_name, val.capitalize()) super(BirthCertificate, self).save(*args, **kwargs) If I comment the save_capitalize function : it works very well. But if … -
Django on EB with daphne and workers
I am trying to deploy a django app with channel on elastic beanstalk and haven't been successful. I have configured supervisor in order to run daphne and workers but when I deploy it, supervisor status on daphne and workers goes to FATAL state. I have followed this tutorial: http://blog.mangoforbreakfast.com/2017/02/13/django-channels-on-aws-elastic-beanstalk-using-an-alb Here is my supervisord.conf [unix_http_server] file=/opt/python/run/supervisor.sock ; (the path to the socket file) ;chmod=0700 ; socket file mode (default 0700) ;chown=nobody:nogroup ; socket file uid:gid owner [supervisord] logfile=/opt/python/log/supervisord.log ; (main log file; default $CWD/supervisor.log) logfile_maxbytes=10MB ; (max min logfile bytes b4 rotation;default 50MB) logfile_backups=10 ; (num of main logfile rotation backups;default 10) loglevel=info ; (log level;default info; others: debug,warn,trace) pidfile=/opt/python/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid) minfds=1024 ; (min. avail startup file descriptors;default 1024) minprocs=200 ; (min. avail process descriptors;default 200) directory=/opt/python/current/app ; (default is not to cd during start) ;nocleanup=true ; (don't clean up tempfiles at start;default false) [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///opt/python/run/supervisor.sock [program:httpd] command=/opt/python/bin/httpdlaunch numprocs=1 directory=/opt/python/current/app autostart=true autorestart=unexpected startsec=1 ; number of secs prog must stay running (def. 1) startretries=3 ; max # of serial start failures (default 3) exitcodes=0,2 ; 'expected' exit codes for process (default 0,2) killasgroup=false ; SIGKILL the UNIX process group (def false) redirect_stderr=false [program:Daphne] environment=PATH="/opt/python/run/venv/bin" … -
KeyError at /accounts/regist/
I got an error,KeyError at /accounts/regist/ 'email'. Before,my user registration form had username&password column only.I wanna add email form into it, so I wrote it.But I got the error.I imported django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm. And my auth_user table has email column , so I do not know how to fix it. I wrote in test.py from django.test import TestCase # Create your tests here. class UserTests(APITestCase): def setUp(self): """ setUp for testing """ User.objects.create(username='user1', email='email1', password='user1') User.objects.create(username='user2', email='email2',password='user2') self.user1 = User.objects.get(username='user1') self.user2 = User.objects.get(username='user2') in serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'username','email', 'password') write_only_fields = ('password') read_only_fields = ('id') def create(self, validated_data): password = validated_data.get('password') validated_data['password'] = make_password(password) return User.objects.create(**validated_data) in forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm class RegisterForm(UserCreationForm): def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' In these codes,I designated email column.So,what should I do to fix it? -
Ckeditor and Django error: red X image
Migrated a site where ckeditor was working and images could be uploaded however now that doesn't work. It's settings are MEDIA_ROOT = os.path.join(DIR_PATH, 'media/') CKEDITOR_UPLOAD_PATH = MEDIA_ROOT + "/image-uploads/" snapshot of error the image exists on the path /home/ubuntu/webapps/kenyabuzz/kb/media/image-uploads/2017/02/16/screenshot-from-2017-02-15-12-48-34.png prior working link did not have the full path /media/image-uploads/2017/02/16/screenshot-from-2017-02-16-15-35-35.png -
Saving valid JSON into JSONField via Django Rest Framework
I'm using Django version 1.10.5 and Django Rest Framework 3.5.3 I als installed pip install jsonfield. My model has this field: tags = JSONField(blank=True, default="") This is the data I send to my server: { "latitude": 31.65431, "longitude": -28.29471, "accuracy": 5, "upload_type":"3", "share_group":1555, "description": "Testing a event from mobile application", "timestamp": "2017-02-16T09:27:23Z", "tags": [{"tagId": 29,"values": [{"fieldId": 193,"value": "CYX 544 GP"},{"fieldId": 194,"value": ""}]}] } I get this error: "tags": ["Not a valid string."] The only way to get this to save is this: "tags":[{'tagId': 29,'values': [{'fieldId': 193,'value': 'CYX 544 GP'},{'fieldId': 194,'value': ''}]}]" Sure, I can just do a replace("'",'"") to get this to be valid json, but this seems like a hack. How am I supposed to send JSON and save it as JSON using the rest framework? -
How to handle POST in CBV using form wizard and formset?
I want to select some objects at the first step of the form wizard and get them at post handler of my view to proceed them. Objects are defined from queryset with the parameter, established at the zero step of wizard. What hanler of classbased view W3_MakeEstim(SessionWizardView) and how must I define? Can anybody show an example code? urls.py: url(r'^makeestim$', W3_MakeEstim.as_view([W1_ParamForm, W3_SelectForm]), name='makeestim'), views.py: class W3_MakeEstim(SessionWizardView): template_name = "w3_makeestim.html" def done(self, form_list, **kwargs): fData = [form.cleaned_data for form in form_list] return render(self.request, 'w1_done.html', {'form_data': fData}) def get_form(self, step=None, data=None, files=None): form = super(W3_MakeEstim, self).get_form(step, data, files) step0data = self.storage.get_step_data('0') """ creating queryset with parameter, got at the zero step populating list with dicts, handling queryset values ctreating formset and initialising it """ RealEstateFormSet = formset_factory(RealEstateForm, extra = 0) oEstates = RealEstateFormSet(initial = list) return oEstates forms.py: # Form class class RealEstateForm(forms.Form): def __init__(self, *args, **kwargs): super(RealEstateForm, self).__init__(*args, **kwargs) self.fields['id'] = forms.IntegerField() self.fields['district'] = forms.CharField() self.fields['square'] = forms.CharField() self.fields['priceM'] = forms.CharField() template: ... {% if wizard.form.forms %} {# formset? #} <table> {% for form in wizard.form.forms %} <tr> <td><input name="1-oEstates" id="id_1-oEstates_{{form.id.value}}" type="checkbox" value="{{form.id.value}}" /></td> <td>{{ form.district.value|default_if_none:"" }}</td> <td>{{ form.square.value }}</td> <td>{{ form.priceM.value }}</td> </tr> {% endfor %} </table> ... -
Images on amazon s3
beginner with development and I got two problems trying to deploy on heroku using amazon s3 to handle the images, locally it is working normally but after deploy it get those problems, first my jumbotron does not show the image, that image it is on amazon s3 but others images on the web site it's being shown, second problem it is my register when I try to register I get 500 error I'm using django-registration-redux to handle it. this is the link to https://multi-ecommerce.herokuapp.com/ my product model.py class ProductQuerySet(models.query.QuerySet): def active(self): return self.filter(active=True) class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model, using=self._db) def all(self, *args, **kwargs): return self.get_queryset().active() def get_related(self, instance): products_one = self.get_queryset().filter(categories__in=instance.categories.all()) products_two = self.get_queryset().filter(default=instance.default) qs = (products_one | products_two).exclude(id=instance.id).distinct() return qs class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(max_length=120) description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=20) active = models.BooleanField(default= True) categories = models.ManyToManyField('Category', blank=True) default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True) objects = ProductManager() def __str__(self): return self.title def get_absolute_url(self): return reverse("product_detail", kwargs={"pk": self.pk}) def get_image_url(self): img = self.productimage_set.first() if img :`enter code here` return img.image.url return img #None class Variation(models.Model): product = models.ForeignKey(Product) title = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2, max_digits=20) sale_price = models.DecimalField(decimal_places=2, max_digits=20, null=True) active = models.BooleanField(default= … -
Django : NoReverseMatch at when changing password using form
I'm trying to make form and method which allows users to change their password. When user type their password into two inputs than form will check if those are same and update db. However I got this error and I couldn't solve it. error message NoReverseMatch at /blog/password_change/blue/ Reverse for 'profile' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'blog/profile/(?P<username>[-\\w.]+)/$'] urls.py url(r'^password_change/(?P<username>[-\w.]+)/$', views.password_change, name='password_change'), views.py def password_change(request, username): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect(reverse('blog:profile')) else: return redirect(reverse('blog:profile')) else: form = PasswordChangeForm(user=request.user) return HttpResponseRedirect('/blog/') profile.html. this is the template. <form class="form-horizontal" role="form" action="{% url'blog:password_change' user.username %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="password1">new password</label> <div class="row"> <input type="password" name="password1" id="password1"/></div> <div class="row"> <label for="password2">password check</label></div> <div class="row"> <input type="password" name="password2" id="password2"/></div> <div class="row"> <button type="submit" class="button-primary">change password</button></div> views.py def password_change(request, username): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect(reverse('blog:profile')) else: return redirect(reverse('blog:profile')) else: form = PasswordChangeForm(user=request.user) return HttpResponseRedirect('/blog/') This is forms.py class PasswordChangeForm(forms.ModelForm): error_messages = { 'password_mismatch': ("The two password fields didn't match."), } password1 = forms.CharField( label=("Password"), strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=("Enter the … -
Using GeoDjango in model with datetime stamp
I have model in django which looks like below from django.db import models from django.contrib.gis.db import models class SignBoard(models.Model): location=models.PointField(blank=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) class SignBoardData(models.Model): signboard=models.ForeignKey(SignBoard,related_name="data") content_eng = models.TextField() content_hind = models.TextField() def __str__(self): return self.content_eng def __unicode__(self): return '%d: %s' % (self.id,self.content_eng) I have enabled postgis extension in my postgresql database. On migrating the above model. i get an error . File "../.../local/lib/python2.7/site-packages/django/contrib/gis/db/models/fields.py", line 245, in get_prep_value raise ValueError('Cannot use object with type %s for a spatial lookup parameter.' % type(obj).name) ValueError: Cannot use object with type datetime for a spatial lookup parameter. I thought that the datetime field is causing the issue but that's not true.Any idea what may be the cause of it? -
Django form - custom form validation
I have a form in which I display calculated data from the database, two dropdowns in which you can choose for each month/year which data to see, how can I custom validate this form so it will return data when I select data/year? from django.views.generic.edit import FormView from django.utils import timezone from .models import Rate from .forms import StatisticsForm from .services import StatisticsCalculation class StatisticsView(FormView): template_name = "statistics/custom_statistics.html" form_class = StatisticsForm def get_initial(self): """TODO: Init form field :returns: TODO """ initial = super(StatisticsView, self).get_initial() initial["month_choice"] = timezone.now().month initial["invoice_year"] = timezone.now().year return initial def get_context_data(self, **kwargs): """TODO: Init Statistics Table :returns: TODO """ context = super(StatisticsView, self).get_context_data(**kwargs) currency = Rate.EUR context["can_view"] = self.request.user.is_superuser context["currency"] = default_currency context["statistic"] = StatisticsCalculation.\ statistic_calculation(default_currency) return context -
Django - ManyToManyField does not let me save, "This field is required" even though I select something
I have a formset like so: class TransactionForm(ModelForm): def __init__(self, *args, **kwargs): try: user = kwargs.pop("user") except KeyError: user = None super(TransactionForm, self).__init__(*args, **kwargs) self.fields["date"].widget.attrs["class"] = "datepicker" if user is not None: self.fields["categories"].queryset = Category.objects.get_all(user) self.fields["account"].queryset = Account.objects.for_user(user) class Meta: model = Transaction exclude = [""] TransactionFormSet = modelformset_factory(Transaction, form=TransactionForm, exclude=("",)) View: def transaction_create_view(request, account_id=None): if request.method == "POST": formset = TransactionFormSet(request.POST) print(formset.errors) if formset.is_valid(): for form in formset: if form.is_valid and form.has_changed(): form.save() if account_id is not None: transactions = TransactionFormSet(queryset=Transaction.objects.for_account(account_id, request.user)) else: transactions = TransactionFormSet(queryset=Transaction.objects.for_user(request.user)) transactions.form = curry(TransactionForm, user=request.user) transactions.forms.insert(0, transactions.forms[-1]) del transactions.forms[-1] context = {"transactions":transactions,} return render(request, "transactions/transactions.html", context) Model: class Transaction(models.Model): account = models.ForeignKey(Account) date = models.DateField() payee = models.CharField(max_length = 100) categories = models.ManyToManyField(Category) comment = models.CharField(max_length = 1000) outflow = models.DecimalField(max_digits=10, decimal_places=3) inflow = models.DecimalField(max_digits=10, decimal_places=3) cleared = models.BooleanField() class Category(models.Model): title = models.CharField(max_length = 100) subcategory = models.ForeignKey("self", blank=True, null=True) user = models.ForeignKey(User) budget = models.DecimalField(max_digits=10, decimal_places=2) And template: <form action="{% url 'transaction_create' %}" method="post"> {% csrf_token %} {{ transactions.management_form }} {% for form in transactions %} {{ form.as_p }} <input type="submit" value="Save transaction" /> <hr> {% endfor %} </form> I input information in the empty form it produces and click on the … -
limiting file extension in django form file upload
I have forms.Form in django. In this form there is a forms.FileField. This field is rendered in html as <input id="id_upload-loaded_file" name="upload-loaded_file" type="file"> I need to add accepted files only with ".zip" extension so that form will be rendered as <input id="id_upload-loaded_file" name="upload-loaded_file" type="file" accept=".zip"> How can I add accepted file extension attribute in django? -
heroku django failed to detect set buildpack
I was trying to deploy a Django app on Heroku. but this is the error I face: Failed to detect set buildpack https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz I have tried everything I could. no help what could be wrong? this is the project structure: project name: api_test and directories: api_main api_test check.py db.sqlite3 manage.py Procfile requirements.txt runtime.txt venv this is requirements.txt: appdirs==1.4.0 beautifulsoup4==4.5.3 bs4==0.0.1 Django==1.10.5 djangorestframework==3.5.4 gunicorn==19.6.0 packaging==16.8 pyparsing==2.1.10 six==1.10.0 and this is runtime.txt: python-3.6.0 I tried to add buildpack, but it fails -
Django query sum values from related table
I have two tables: Ticket Table id paid_with_tax 1 5 2 6 3 7 TicketAdjustment Table id ticket_id value_with_tax 1 1 2 2 1 1 3 1 2 4 1 3 5 2 5 The query I use: use = 0 Ticket.objects.all().annotate( paid_amount=Sum( F('paid_with_tax') + Coalesce(F('ticketadjustment__value_with_tax'), 0) * use ) ) the query would return the following: [ {id: 1, paid_amount: 7}, {id: 1, paid_amount: 6}, {id: 1, paid_amount: 7}, {id: 1, paid_amount: 8}, {id: 2, paid_amount: 11}, {id: 3, paid_amount: 7}, ] but the above is incorrect when I try to use the values. how can i get the query to sum the ticketadjustments valaues and return the following: [ {id: 1, paid_amount: 13}, {id: 2, paid_amount: 11}, {id: 3, paid_amount: 7}, ] -
OR query in django-filter
I am having difficulty to implement OR query using django-filter. I could find some example telling how to create OR query in django queryset. But, I could not find in django-filter documentation. Does anyone know how to implement OR query using django-filter? model.py and filter.py is shown below. model.py class html(models.Model): project = models.CharField(max_length=50, blank=True) version = models.IntegerField(default=0) ecms=models.ManyToManyField(ecm, blank=True) diff = models.TextField(blank=True) PROGRAM_CHOICES = ( ('Office', 'General office'), ('Residential', 'Residential'), ('Retail', 'Retail'), ('Restaurant', 'Restaurant'), ('Grocery', 'Grocery store'), ('Medilcal', 'Medilcal office'), ('Research', 'R&D or laboratory'), ('Hotel', 'Hotel'), ('Daycare', 'Daycare'), ('K-12', 'Educational,K-12'), ('Postsecondary', 'Educational,postsecondary'), ('Airport', 'Airport'), ('DataCenter','Data Center'), ('DistributionCenter','Distribution center,warehouse') ) program = models.CharField(max_length=20, choices=PROGRAM_CHOICES, default='Retail') LOCATION_CHOICES = ( ('Beijing', 'Beijing'), ('China', 'China'), ('Hong Kong', 'Hong Kong'), ('Japan', 'Japan'), ('Shanghai', 'Shanghai'), ('Shenzhen', 'Shenzhen'), ('Taiwan', 'Taiwan') ) location = models.CharField(max_length=15, choices=LOCATION_CHOICES, default="Hong Kong") CERTIFICATE_CHOICES = ( ('LEED_v3', 'LEED_v3'), ('LEED_v4', 'LEED_v4'), ('BEAM+', 'BEAM+'), ('WELL', 'WELL') ) certificate = models.CharField(max_length=10, choices=CERTIFICATE_CHOICES, default='BEAM+') user = models.CharField(max_length=20, default='test') html = models.FileField(upload_to=dir_path) uploaded_at = models.DateTimeField(auto_now_add=True) filter.py import django_filters from .models import html class ProjectFilter(django_filters.FilterSet): class Meta: model=html fields=['project','program','location','certificate','user'] -
django bubble chart js how to return multiple datasets
I am using chart js to make a bubble chart, How do you return multiple datasets, What I have tried so far only returns the first dataset that is created. view.py class BubbleChart(Chart): chart_type = 'bubble' responsive = False def get_datasets(self, **kwargs): set1 = [{ 'x': random.randint(1, 10), 'y': random.randint(1, 25), 'r': random.randint(1, 10), } for i in range(25)] return [DataSet(label="First DataSet", data=set1, backgroundColor='#FF6384', hoverBackgroundColor='#FF6384'), ] set2 = [{ 'x': random.randint(1, 10), 'y': random.randint(1, 25), 'r': random.randint(1, 10), } for i in range(25)] return [DataSet(label="First DataSet", data=set2, backgroundColor='#33FF33', hoverBackgroundColor='#33FF33'), ] data = [set1, set2] def bubble(request): return render(request, 'polls/chart.html', { 'bubble': BubbleChart(), }) -
Django model delete error after removing model from application
I had completed some refactoring of applications in a Django 1.8 project, and one result was an application's model file was made superfluous and not needed anymore. So, I deleted the file and ran migrations. Now, when I try to delete a model that once related to that table via a FK relationship, I get a MySQL error 1146, table does not exist anymore. What is odd with this is the delete query works fine in straight SQL, but not in the Django ORM. Things I've done: Deleted the app_label from contenttypes Ran migrations, no errors Checked SHOW CREATE application_catalog, all FK keys referencing deleted table don't exist anymore. Restarted Apache server. Now, when I do something like c = Catalog.objects.get(pk = 1145) c.delete() I get that MySQL error 1146. However, if I execute the SQL delete from project.application_catalog where id = 1145; the delete query has no errors and the record is successfully removed -
Using DateTime as text in Django's filter
I have a DB table with many rows in it and there is a DateTimeField column in the DB table. I implemented a custom HTML table where there is a textfield above each column to filter the HTML table. I am planning to display this DateTime in the HTML table and give the opportunity to the user to filter the data by the date time. Let's say that I will display the date time like '2017.02.16 12:51:34' and the user can either write '2017.02' (to display the 2017 February data) or '02.16 12' (to display the February data on each year that was created between 12:00:00 and 12:59:59) or etc. I want to add this logic to the filter part of the query set because there are many rows in the table and I want to execute one SELECT for performance reasons. Also I have other things to add to the filter part (just filter simple text values) so writing the raw SELECT might not be the solution. Not to mention that I should write SELECTs for different databases ... Is there any solution in Django for that? Or do I have to write the native query? Thanks, V.