Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
BugSnag, Django and the before_notify calback
BugSnag's documentation suggests this for custom fields: def callback(notification): # if you return False, the notification will not be sent to # Bugsnag. (see ignore_classes for simple cases) if isinstance(notification.exception, KeyboardInterrupt): return False # You can set properties of the notification and # add your own custom meta-data. notification.user = {"id": current_user.id, "name": current_user.name, "email": current_user.email} notification.add_tab("account", {"paying": current_user.acccount.is_paying()}) # Call `callback` before every notification bugsnag.before_notify(callback) my application is JWT token based internl-api application server. Meaning, I don't have a current_user or any users "logged in" for that matter. Is there any way to get to the user of the current request? in views it's available as request.user after the JWT middleware parses out the token but how do I apply it here into this callback? I don't have access to the request object? notification.request doesn't exist. -
Django's Token based Authentication without User model
I am using Django Token based Authentication. (JWT Token is generated by third party like AWS Cognito, we will just verify signature and expiry time). This REST Application will not have any user models, whoever consuming the API calls need to be authenticated by JWT token only. class JSONWebTokenAuthentication(TokenAuthentication): def authenticate_credentials(self, jwtToken): try: payload = jwt.decode(jwtToken, secret_key,verify=True) # user = User.objects.get(username='root') user = AnonymousUser() except (jwt.DecodeError, User.DoesNotExist): raise exceptions.AuthenticationFailed('Invalid token) except jwt.ExpiredSignatureError: raise exceptions.AuthenticationFailed('Token has expired') return (user, payload) In Views: @api_view(["POST"]) @authentication_classes((JSONWebTokenAuthentication,)) @permission_classes((AllowAny,)) Above process, doesn't keep track of Token at all. With/Without Token, APi calls are working. If i make below two changes, it is working. user = User.objects.get(username='root') #user = AnonymousUser() @permission_classes((IsAuthenticated,)) One way to do it is, to have atleast one user in my app and reference that user[ This webapp might scale to any number of instances when needed, so inserting the same user with same "username" has to be automated. ]. But instead, can i eliminate "User" concept in Authentication? -
How to show user activity in modal by django-activity-stream app?
Can someone who worked with app django-activity-stream say me how to use it correctly by example? I am really comfused after reading the documentation. I need to show last 10 activity which was in my modal Characterictic. User can edit Characterictic objects also add comments to objects. For example: 1) User A add comment to Characterictic B in 11:45 2) User B edit Characterictic C in 11:00 3) User C create Characterictic А in 09:55. models.py: class Characteristic(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) symbol = models.CharField(_('Symbol'), max_length=250) description = models.TextField(_('Description')) comments = models.ManyToManyField("Comment") create_time = models.DateTimeField(_('Date of creation'), auto_now_add=True) revision_date = models.DateTimeField(_('Date of last update'), auto_now=True) class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() created = models.DateTimeField(auto_now_add=True) -
DRf, handle unhandled exception
When using DRF, Django's ValueError (django.core.exceptions) and IntegrityError (django.db) is not handled. DRF's def exception_handler has exception handling code for (APIException, Http404, PermissionDenied) Below is a code for Http404 elif isinstance(exc, Http404): msg = _('Not found.') data = {'detail': six.text_type(msg)} set_rollback() return Response(data, status=status.HTTP_404_NOT_FOUND) So I can create my custom exception handler as def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) if isinstance(exc, ValidationError) or isinstance(exc, IntegrityError): data = { 'errors': str(exc) } set_rollback() # not sure about this line response = Response(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return response I'm not sure about the purpose of set_rollback() line in the code, and not sure if I'm safe with this code. -
Serialize Django Queryset to JSON for Celery before execution
I am given a Queryset from an external library and - since Querysets are lazy - I'd like to serialize it to JSON before it is accessed, and thus executed, in the DB, so it may be executed in an asynchronous Celery task instead. Is there a way of representing the essential elements of a Queryset as JSON so I don't have to use Pickle? I know I could get the raw query with queryset.query, but since I'd have to execute a raw query at the other end, I don't much like that idea. -
Compare form date values in the view
I have a django form which has date fields filled by the user and need to compare them for validity. Anyway the following conditions evaluate to false always. As I'm new to django, I'm not sure is this the right way to do it. start_date = form_new_task.cleaned_data['start_date'] end_date = form_new_task.cleaned_data['end_date'] if start_date < date.today(): err_str = 'Start date cannot be a past date.' elif end_date < date.today(): err_str = 'End date should be a future date.' elif start_date == end_date: err_str = 'Start and End date cannot be the same date.' elif end_date < start_date: err_str = 'End date should be beyond the Start date.' -
Django PasswordChangeForm AttributeError: 'PasswordChangeForm' object has no attribute 'cleaned_data'
I'm received an attributeError whenever I try to change my password as a logged-in user. I'm using Django's built-in PasswordChangeForm. Can anyone help? Here's my views.py: from django.shortcuts import render, redirect from accounts.forms import ( RegistrationForm, EditProfileForm ) from django.contrib.auth.models import User from django.contrib.auth.forms import ( UserChangeForm, PasswordChangeForm ) # Create your views here. def home(request): numbers = [1,2,3,4,5] name = 'Matthew Zayas' args = {'myName': name, 'numbers': numbers} return render(request, 'accounts/home.html') def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/account') else: form = RegistrationForm() args = {'form': form} return render(request, 'accounts/reg_form.html', args) def view_profile(request): args = {'user': request.user} return render(request, 'accounts/profile.html', args) def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid: form.save() return redirect('/account/profile') else: form = EditProfileForm(instance=request.user) args = {'form': form} return render(request, 'accounts/edit_profile.html', args) def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid: form.save() return redirect('/account/profile') else: form = PasswordChangeForm(user=request.user) args = {'form': form} return render(request, 'accounts/change_password.html', args) I'm not sure what I've done wrong here since most of the work is being handled by Django right? Any pointers would be much appreciated! -
why uwsgi times out when celery/rabbitmq is stuck?
I have a Django view in which an async task is called, like this def view(request): do_stuff() async_celery_func.delay() The celery task was run at another machine (call it ec2_task). What happened is ec2_task somehow can't take any task, and the view function times out. Why the request itself would timeout when async_task gets wrong? -
how to set the number to become 4 decimal places
I have this code tableyy = final.style.apply(color, axis=None).set_table_attributes('border="" class = "dataframe table table-hover table-bordered"').set_precision(4).render() set_precision(4) I wish to make it my value to become 4 decimal places, but for some value still return me 5 decimal places for example 0.03045. So anyone can share me how to replace the set_precision so that my value all return in 4 decimal places but not 4 significant value. -
Seeding a MySQL DB for a Dockerized Django App
I am tasked with creating a click-button style use of Docker for developers of a Django app to do local development. I am using docker-compose in combination with private repos on my Docker Hub and it's working well. Except that the app has no default data. The developers have requested to use a full prod dump rather than fixtures with loaddata. Therefore I built a container based on this Dockerfile FROM python:2.7 COPY . /opt/mysite.com WORKDIR /opt/mysite.com ENV WAITFORIT_VERSION="v1.3.1" RUN wget -q -O /usr/local/bin/waitforit https://github.com/maxcnunes/waitforit/releases/download/$WAITFORIT_VERSION/waitforit-linux_amd64 \ && chmod +x /usr/local/bin/waitforit RUN curl -sL https://deb.nodesource.com/setup_6.x | bash - RUN apt-get -y update && apt-get -y install mysql-client nodejs RUN pip install -r requirements/local.txt RUN npm install RUN ./node_modules/.bin/babel-node ./node_modules/.bin/webpack CMD waitforit -full-connection=tcp://mysql:3306 -timeout=60 -debug && mysql -u root -h mysql --password=**** organicvalley_develop < prod.sql && /bin/bash -c "source /opt/organicvalley.com/env.local && python manage.py collectstatic --noinput && python /opt/organicvalley.com/manage.py runserver 0.0.0.0:5000" All works well except that it takes a very long time to be able to see localhost:5000 after the containers are up. Therefore I started to investigate data-only containers, but I am wondering what happens when I push that container to Docker hub? Can it be pulled with the mysql data baked … -
How should appropriate Django session template look like?
I'm not sure I use Django session in appropriate way. To login I use this view and URL (Is it OK?): url(r'^login/$', views.my_login): from django.contrib.auth import authenticate, login @api_view(['POST']) def my_login(request): if request.method == 'POST': username = request.POST.get('username', '') password = request.POST.get('password', '') user = authenticate(username=username, password=password) if user is not None: if user.is_active: request.session.set_expiry(86400) login(request, user) In every method that requires authentication I use if request.user.is_authenticated() or @login_required If this is a good method how can I use both @api_view(['GET', 'POST']) and @login_require? It seems to me that it isn't a good solution: @login_require @api_view(['GET', 'POST']) def my_func(request): #... Thanks in advance for your help and opinions. -
Python Django + Z3 Segmentation fault
I am trying to build a Django web application using Python 3.4.3 and Anaconda virtual environments. The application involves using ANTLR and the Z3 proof checker. I am getting a segmentation fault error deterministically (every run) somewhere in the Z3 code (discovered this by having prints in the code). The errors occur for any input given when sending the requests via the Django web server. Everything works fine if I just run the ANTLR + Z3 function I am interested in with the same input. Also, the seg faults occur after one commit which seems to not affect the file in question in any way. Relevant files presented below: # Types.py import uuid import sys sys.path.insert(0, '/Users/username/project_name/theorem_prover') from rest_framework import serializers from app.api.models.Proof import Proof from django.db import models from Z3TypeBuilder import Z3TypeBuilder class Type(models.Model): proofId = models.ForeignKey(Proof) text = models.CharField(max_length=300) @classmethod def is_valid(cls, types): type_builder = Z3TypeBuilder(dict(), dict()) valid = type_builder.visitInputArray(types) return valid @classmethod def get_maps(cls, types): param_map = dict() predicate_map = dict() type_builder = Z3TypeBuilder(param_map, predicate_map) valid = type_builder.visitInputArray(types) return valid, param_map, predicate_map class TypeSerializer(serializers.ModelSerializer): class Meta: model = Type fields = ('id', 'proofId', 'text') The one above is the file representing the model for Types import logging … -
Making query from a list with varying amount of values
I have for example the following lists: list1 = ['blue', 'red'] list2 = ['green', 'yellow', 'black'] How could i create a query searching for all values (using postgresql). This will work fine but it's hardcoded for only two values and therefore not handling the varying amount of values of the lists. entry.objects.annotate(search=SearchVector('colors')).filter(search=SearchQuery('blue') | SearchQuery('red')) I tried the following to create a 'search_query' string and place it in my query: for c in color: search_string += "SearchQuery('" + c +"') | " search_string = search_string[:-3] This will result in the following search_strings SearchQuery('blue') | SearchQuery('red') SearchQuery('green') | SearchQuery('yellow') | SearchQuery('black') If i now put this string in my query, it will not work. entry.objects.annotate(search=SearchVector('colors')).filter(search=search_string) I appreciate any help to solve this problem. Link to django postgres search documentation: https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/search/ -
Manytomany field is None and can't create or add field to model. How do I add the field?
My models are set up as follows: class Person(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='person_user') type = models.IntegerField() class Score(models.Model): person = models.ForeignKey(Person, related_name='person') score = models.FloatField(default=0) I can create Score objects fine and create a relation to the Person. However, the next part is causing some difficulty. I added Score after I had already created the following fields (except for the very last line): class Applicant_Response(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user') interview = models.ForeignKey(Interview, related_name='interviews') extra_information = models.ForeignKey(ExtraInformation, related_name='extra_information', null=True, blank=True) score = models.ManyToManyField(Score, related_name='applicant_score', default=1) I created a Score object that had a score of 0 and a person to use as the default for score (was assigned an ID of 1). However, when I tried accessing the field score in the Applicant_Response, I get profiles.Score.None, which confuses me (profiles is the name of the application). To my understanding, I am not able to add anything to the manytomany field because it does not exist? Maybe the way I am trying to add Score to Applicant_Response is incorrect?: try: applicants = models.Applicant_Response.objects.filter(interview=interviews) for applicant in applicants: applicant.score.add(models.Score.objects.get(id=1)) applicant.save() print applicant.score except Exception as e: print e I get the following in stdout: profiles.Score.None How do I add a Score to the … -
how to solve the 'dict' object has no attribute '_meta'
I am trying to retrieve some data from a web API because I want to display it in the browser and I want to manipulate it by assigning this data to a variable so I can manipulate the data but I am encountering the error: 'dict' object has no attribute '_meta'. Views from django.core import serializers from rest_framework.views import APIView from rest_framework.response import Response import json, urllib.request from django.views.generic import View from django.http import JsonResponse def get_data(request, *args, **kwargs): with urllib.request.urlopen("http://10.61.202.98:8081/T/ansdb/api/rows/dev/tickets?id=1003611",timeout=10) as url: response_data = json.loads(url.read().decode()) response_data_serialized = serializers.serialize('json',response_data) return JsonResponse(response_data_serialized, safe=False) URLs urlpatterns = [ url(r'^$', views.index, name='index'), # home url(r'^statistics/$', views.statistics, name='statistics'), url(r'^statistics/data$', get_data, name='get_data'),] The data that I want to retrieve has the following format: [{ id: 100361324, Aging_Deferred_Transferred: "", Aging_Open_Issue: "", Aging_Un_investigated_Issue: "", CreatedBy: "userx@.....com", DeltaQD: null, DeltaQDBadAttempts: null, Escalation_Category: "", Golden_Cluster: "", Incident_DateTime: "2017-02-01 Week: "8", Weekend_Flag: "Yes" }] Some links I read were Django JSON:: 'dict' object has no attribute '_meta' and Django1.9: 'function' object has no attribute '_meta' but in those links the solutions do not fit my problem. Any help on how to solve this is welcome. -
Accessing "self" in save method of class-based model
I have two models that look like this: class ModelOne(models.Model): foo = models.CharField(max_length=25) def save(self,*args,**kwargs): a = ModelTwo.objects.get(pk=arbitrary_pk) a.somefield.add(self) # I am worried about this line here super(ModelOne,self).save(*args,**kwargs) class ModelTwo(models.Model): somefield = models.ManyToManyField(ModelOne) The line where I am adding self to a.somefield is the line I am worried about. How can I do this without error? Currently, I am getting: ValueError: Cannot add "<ModelOne>": the value for field "modelone" is None Thanks in advance -
Django formsets business logic
I have 2 models, one for "Sale order head" and order for "sale order item". class PanSaleOrderHead(GenericCommonModel, GenericFieldCompany): customer = custom_model_fields.PanForeignKey('pancrm.PanCustomer', verbose_name=_('customer')) currency = models.ForeignKey(PanBasCurrency, verbose_name=_('currency')) sub_total = custom_model_fields.PanSubTotalField() vat_amount = custom_model_fields.PanVatAmountField() grand_total = custom_model_fields.PanGrandTotalField() is_delete = custom_model_fields.PanIsDeleteField() class PanSaleOrderItem(GenericCommonModel): sale_order_head = models.ForeignKey(PanSaleOrderHead, verbose_name=_('sales head')) material = custom_model_fields.PanForeignKey(PanMaterial, verbose_name=_('material')) price = custom_model_fields.PanPriceField() quantity = custom_model_fields.PanQuantityField() qunit = models.ForeignKey(PanBasQunit, verbose_name=_('unit'), default='') sub_total = custom_model_fields.PanSubTotalField() vat_amount = custom_model_fields.PanVatAmountField() grand_total = custom_model_fields.PanGrandTotalField() Dont bother understanding the models, PanSaleOrderHead keeps track of customer and PanSaleOrderItem keeps track of materials. I have save button and actualize button on my form, actualize button refreshes the values like sub_total,grand_total,vat_amount like fields and do other validations for user to see if there is an error, without actually saving the model. Save button does the same thing actualize button does and saves the form to db. I tried to put business logic in form, but this caused models beeing saved in admin or other sources, misses this logic, its not like pre_save method. If I put this logic to pre_save method or signal, I can update other fields just before save and make sure they are correct but, this means, user cant actualize the form, he has to save … -
How do I make a query into a field in Django
This is probably a very simple question but I can't figure it out. The way my User model is set up is that they have a Profile attached to it and in the Profile there is a value for Coins. I would like to return the top 10 users by coins so I thought that something like: User.objects.all().order_by('coins')[:10] would work, but the problem is that the coins are attached to the profile. .order_by('profile.coins') doesn't seem to work either. -
objects deleted from table still persist when accessing model objects via django
I am working on a django app with a postgresql backend. I am working on a separate python script to access the table (model via django) to make some modifcations, then launch web forms for the modified records. In my testing I have gone into the database outside of the script and deleted records, and when I run the script again, the deleted records still persist. Why is this happening and how can I make sure the table is refreshed each time I run the script? I have tried iterating over the objects in the model I am accessing and using object.refresh_from_db() but this doesn't seem to do anything. Can anyone help? -
how to get celery task state?
I am new to Celery and Django. I got the task id using task_id = task.request.id but not able to get the task state. Any suggestion to get the task state? Any help would be appreciated. Thanks! -
How to suppress the 'Invalid class attribute name "id"' pylint warning for Django models?
The default primary key column in Django models is named id, which is not a valid class attribute name according to pylint. How can I suppress the 'Invalid class attribute name "id"' pylint warning for Django model classes (or for the whole project) ? -
Mocking function in a view - Django
I'm new to writing unit tests, this question might be silly but I'm posting this after a lot of research. I'm trying to write a unit test for a function in the centralized/views.py which is being used in a lot of other views. The function looks like this def make_job(self, request, *args, **kwargs): ..... ..... return Response(data, status=status.HTTP_200_OK) I need help in mocking the request in the unit test, since this function is called by other views I'm not sure how to test this function independently without relying on the url path. What is the approach to mock this request? Thanks -
Unable to save checkbox data
i am really exhausted i didn't find any solution for this till now. I was trying to create a table to view all the data save by the user. The problem is that all the inputs in the models.py are saved excluding the parameters with checkbox. I don't know what is the problem. All these parameters in models.py are saved in the database. This is my Models.py : class Parameters(models.Model): user = models.ForeignKey(User) title = models.CharField('title', max_length=100, default='', blank=True, help_text='Use an indicative name, related to the chosen parameters') type = models.CharField('forecast type', choices=FORECAST_TYPES, max_length=20, default="backtest") #input characteristics price_1_min = models.FloatField('1. Price, min', default=0.1, validators=[MinValueValidator(0.1), MaxValueValidator(20000)]) price_1_max = models.FloatField('1. Price, max', default=20000, validators=[MinValueValidator(0.1), MaxValueValidator(20000)]) stocks_num_2_min = models.IntegerField('2. Number of selected stock, min', default=3, validators=[MinValueValidator(0), MaxValueValidator(100)]) stocks_num_2_max = models.IntegerField('2. Number of selected stock, max', default=7, validators=[MinValueValidator(1),]) limit_3 = models.FloatField('3. Last price to upper straight, %', default=20, validators=[MinValueValidator(-200),]) learning_days_4_min = models.IntegerField('4. Number of Learning days, min', default=1, validators=[MinValueValidator(1),MaxValueValidator(30)]) learning_days_4_max = models.IntegerField('4. Number of Learning days, max', default=10, validators=[MinValueValidator(1),MaxValueValidator(30)]) evaluation_days_5 = models.IntegerField('5. Number of Evaluation days', default=10, validators=[MinValueValidator(1),MaxValueValidator(10)]) delay_days_6 = models.IntegerField('6. Number of “no quarterly reports” days (N)', default=10, validators=[MinValueValidator(0),MaxValueValidator(20)]) minimum_gain_7 = models.FloatField('7. Minimum gains for winners', default=0, validators=[MinValueValidator(0),MaxValueValidator(100)]) minimum_loss_8 = models.FloatField('8. Minimum losses … -
Django- Reversing custom Admin URLs
I'm using an App that configures some Admin URLs as: #admin.py.... def get_urls(self): urls = super(FormAdmin, self).get_urls() extra_urls = [ url("^(?P<form_id>\d+)/entries/$", self.admin_site.admin_view(self.entries_view), name="form_entries"), #...... ] return extra_urls + urls I'm having trouble using template tags to get a URL corresponding to that, in one of my templates. I'm trying stuff like: <a href="{% url 'admin:forms_form_entries' form_id=4 %}">4-Entries</a> (Where forms is the App's label). I keep running into the No Reverse Match type of errors: NoReverseMatch at /polls/ Reverse for 'forms_form_entries' with arguments '(4,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] What am I missing that makes the tag work correctly? -
Localized Notifications iOS 10 using FCM
We have a Django backend server using pyfcm to deliver Notifications throgh Firebase Cloud Messaging (FCM). I just updated to the today released Version 1.3.0. I want to send a notification using the loc-key and loc-args parameters so it can be displayed in the language the user is using on his phone. The notification reaches the device, it vibrates and makes the default sound for a new notification, but it will not displayed. It just happens nothing except for the sound and vibration. This is the payload generated by the server which is sent to the fcm endpoint: { "notification": { "loc-args": ["Demo (@demo)"], "loc-key": "notification-follow", "sound": "Default" }, "priority": "high", "to": "..." } On the client side, this is what is received by the phone: [ AnyHashable("gcm.message_id"):0:1496257581534217 %f910cc44f910cc44, AnyHashable("aps"):{ category = profile; sound = Default; }, AnyHashable("gcm.notification.alert"):{ "title-loc-key":" notification-follow", "title-loc-args":[ "Demo (@demo)" ] } ] Is there anything I have to do before the message is displaying? Sending the message without the loc-key and loc-args but with message-body presents the notificaion on the device. Maybe the payload is wrong? How should it look like to do what I want? The key, notification-follow in this case, is listed and translated …