Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allow staff user to only read the data
I want to allow the staff users to view (read only)the transaction data. But when I login as a staff user, it displays 'You don't have permission to edit anything.' and rest of the page is blank. models.py #models.py from django.db import models from django.contrib.auth.models import Permission, User from django.core.validators import RegexValidator # Create your models here. alphanumeric = RegexValidator(r'^[0-9a-zA-Z-]*$', 'Only alphanumeric characters and "-" are allowed.') TransactionTypes = ( ('P','Purchase'), ('S','Sell'), ) class Transactions(models.Model): client_name = models.OneToOneField(User(is_staff=True)) transaction_type = models.CharField(choices=TransactionTypes,max_length=1) amount = models.IntegerField() transaction_id = models.CharField(max_length=50, blank=True, null=True, validators=[alphanumeric]) class Meta: permissions = ( ('read_item','Can read item'), ) Admin.py- #admin.py from django.contrib import admin from django.contrib.auth.models import User from .models import Transactions # Register your models here. class TransactionAdmin(admin.ModelAdmin): #list_display = ('client_name', 'transaction_type', 'amount', 'transaction_id') list_display = ('client_name', 'transaction_type', 'amount', 'transaction_id') def get_readonly_fields(self, request, obj=None): if not request.user.is_superuser and request.user.has_perm('transactionss.read_item'): return [f.name for f in self.model._meta.fields] return super(TransactionAdmin, self).get_readonly_fields( request, obj=obj ) admin.site.register(Transactions, TransactionAdmin) -
Can I change the related_name when I get the nested data in Django-Rest-Framework?
Such as I have two Model, the first is the second's ForeignKey. class MyModel(models.Model): firstDate = models.DateTimeField(auto_now_add=True) another = models.CharField(max_length=30) class MySubModel(models.Model): name = models.CharField(max_length=12) my_model = models.ForeignKey(to=MyModel, related_name="mysubs") In the MyModelSerializer it should be: class MyModelSerializer(ModelSerializer): mysubs = MySubModelSerializer(many=True, read_only=True) class Meta: model = MyModel fields = "__all__" The result will be like bellow: [ { "firstDate":xxxx, "another":xxxx, "mysubs":[ { "name":xxx, } ] } ] I want to replace the key mysubs to children, is it possible to do that? -
How do I access the properties of a many-to-many relationship
How do I access the properties of a many-to-many relationship? and on model. class Courses(models.Model): courses_name = models.CharField(max_length=100) duration = models.CharField(max_length=100) def __str__(self): return u'%s' % (self.courses_name) class Meta: verbose_name_plural = 'Courses' verbose_name = 'Courses' class EducationEntity(models.Model): name = models.CharField(max_length=100) type = models.ForeignKey(EducationEntityType) location_type = models.ForeignKey(LocationType) institute_type = models.ForeignKey(InstituteType) course = models.ManyToManyField(Courses) established=models.DateField(default=datetime.date.today) approved_by=models.CharField(max_length=200) college_facilities=models.CharField(max_length=200) image = models.ImageField(upload_to='images/',default="none") def __str__(self): return u'%s' % (self.name) class Meta: verbose_name_plural = 'Education Entity' verbose_name = 'Education Entity' @property def course_(self): # import ipdb; # ipdb.set_trace() amount='' data = [] duration='' interest_rate='' loan=[] for i in self.course.all(): try: for cou in EducationEntityCourses.objects.filter(course=i): for l in LoanDetails.objects.filter(education_entity_courses__course=i): amount=l.amount for lo in LoanTenure.objects.filter(loan_details__education_entity_courses__course=l): loan.append({"duration": lo.duration,"interest_rate": lo.interest_rate}) except Exception as e: amount='' import ipdb; ipdb.set_trace() data.append({ "courses_name": i.courses_name, "duration":cou.duration, "course_type":cou.course_type, "tution_fees":cou.tution_fees, "hostel_fees":cou.hostel_fees, "other_fees":cou.other_fees, "amount":amount, "loan":loan }) import ipdb; ipdb.set_trace() return data class EducationEntityCourses(models.Model): education_entity = models.ForeignKey(EducationEntity) course = models.ForeignKey(Courses) duration = models.CharField(max_length=100) course_type = models.ForeignKey(CourseType) tution_fees = models.CharField(max_length=100) hostel_fees = models.CharField(max_length=100) other_fees = models.CharField(max_length=100) def __str__(self): return u'%s, %s' % (self.education_entity.name, self.course.courses_name) class Meta: verbose_name_plural = 'Education Entity Courses' verbose_name = 'Education Entity Courses' class LoanDetails (models.Model): education_entity_courses = models.ForeignKey(EducationEntityCourses) # training_coaching=models.ForeignKey(TrainingCoaching,blank=True,null=True) amount = models.CharField(max_length=100) def get_course(self): """ get course name :return: """ return self.education_entity_courses.course.courses_name get_course.short_description="Course Name" … -
Django database routing on request.user
Is it possible to get the user object in Django router class? I'm trying to route query on a database based on the type of user. Is it even possible? Thank you -
How can I run one-off dyno inside another one-off dyno on Heroku using custom django-admin commands?
I need to create one-off dyno in Django application deployed on Heroku using custom django-admin commands. I want to use Heroku Scheduler to run command heroku run python manage.py test_function2. It creates one-off dyno with running function test_function2 in it. Then I would like to use test_function2 function to create more one-off dynos. I added example code below. My problem is associated with line command = 'heroku run:detached myworker2' When I use command = 'heroku run:detached myworker2' in test_function2 I get error sh: 1: heroku: not found. Does anyone have an idea how can I create heroku one-off dyno when I am already in one? test_function2: class Command(BaseCommand): def handle(self, *args, **options): command = 'heroku run:detached myworker2' os.system(command) Procfile: web: sh -c 'gunicorn backend.wsgi --log-file -' myworker2: python manage.py test_function2 myworker2: python manage.py test_function -
Filtering many to many field Django
I have a query like this: queryset = User.objects.filter( ~Q(pk=self.request.user.pk), ~Q(connections_as_initiator__peer=self.request.user, connections_as_initiator__stopped=False)) Beetween one intitator and peer there could be numerous connections bun only one that is not stopped. So what I want this query to do is to find whether between the current user and the queried one there are active connections where the current user is a peer. But this is not what happens at all: SELECT accounts_user.id FROM accounts_user WHERE ( NOT accounts_user.id = 48 AND NOT accounts_user.id IN (SELECT U1.initiator_id AS col1 FROM connection U1 WHERE U1.peer_id = 48) AND NOT accounts_user.id IN (SELECT U1.initiator_id AS col1 FROM connection U1 WHERE U1.stopped = FALSE) ); What I was thinking of (and what gives an expected result) is something like: SELECT accounts_user.id FROM accounts_user WHERE ( NOT accounts_user.id = 48 AND NOT accounts_user.id IN (SELECT U1.initiator_id AS col1 FROM connection U1 WHERE U1.peer_id = 48 AND U1.stopped = FALSE) ); Is there a way to achieve that with ORM or should I start using raw SQL. I was also thinking about annotations, but I'm not yet 100% sure how to implement it that way. -
AttrbuteError while using serializer in djangorestframework
I get 'AttrbuteError: 'DeferredAttribute' has no attribute 'isoformat'' when i try to serialize the django model using the djangorestframework Below is the model that im trying to serialize class PrimaryRecord(models.Model): primaryId = models.AutoField(primary_key=True) primary_track = models.CharField(max_length=30) title = models.CharField(max_length=255) start_date = models.DateField() create_date = models.DateField() year = models.IntegerField() and the serializer class that i'm using is below from rest_framework import serializers from snippets.models import Assesor, PrimaryRecord, PrimaryAssesor class PrimaryRecordSerializer(serializers.Serializer): primary_track = serializers.CharField(max_length=30) title = serializers.CharField(max_length=255) start_date = serializers.DateField(format = None) create_date = serializers.DateField(format = None) year = serializers.IntegerField() def create(self, validated_data): return PrimaryAssesor.objects.create(**validated_data) def update(self, instance, validated_data): instance.primary_track = validated_data.get('primary_track', instance.primary_track) instance.title = validated_data.get('title', instance.title) instance.start_date = validated_data.get('start_date', instance.start_date) instance.create_date = validated_data.get('create_date', instance.create_date) instance.year = validated_data.get('year', instance.year) instance.save() return instance Im following this tutorial for learning djangorestframework. I do the following steps p1 = PrimaryRecord(primary_track='P2017-98',title='ABC',start_date=date(2017,6,23),create_date=timezone().now(),year=2017) p1.save() serializer = PrimaryRecordSerializer(primaryrecord) serializer.data # the error occurs here 'AttrbuteError: 'DeferredAttribute' has no attribute 'isoformat'' -
How can I get the custom nested data in Django?
I have four model as bellow: class AModel(models.Model): name = models.CharField(max_length=11) class BModel(models.Model): name = models.CharField(max_length=11) a = models.ForeignKey(AModel, related_name="bs") class CModel(models.Model): name = models.CharField(max_length=11) b = models.ForeignKey(BModel, related_name="cs") class DModel(model.Model): name = models.CharField(max_length=11) c = models.ForeignKey(CModel, related_name="ds") Now I want to get the bellow data: [ {"name":"a1", "value":1, "image":"xxxxx.png", "children":[ {"name":"b1", "value":1, "image":"xxxxx.png", "children":[ {"name":"c1", "value":1, "image":"xxxx.png", "children":[ {"name":"d1", "value":1, "image":"xxxx.png", } ] } ] } ] } ] note, the value and image key-value are add by myself. I know use the Django-Rest-Framework can get the data like: [ { "id":1, "name":"a1", "bs":[ { "id":1, "name":"b1", "cs":[ "id":1, "name":"c1", "ds":[ { "id":1, "name":"d1", } ] ] } ] } ] But how can I get my requirement data? I also tried query the AModel instance first, the forloop the AModel instance's bs, and then do the next, but I find that is too complex, not a simple and convenient way to get it. -
Basic Authentication in Django Rest Framework
I want to Authenticate the username and password for an API. If the username and password is correct, then it will display the userlist, otherwise NOT. I have stored all the username and password in my own table named USERS. Can you please help how to authenticate the username/password from the USERS table entry. Or all the authentication can be made only from "auth_user" table by default. Please me help me with the code. NOTE: I am using Postgresql as Database. class UsersList(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) def get(self, request): dict_data = {} userlist = Users.objects.all() if userlist: serializer = UserlistSerializer(userlist, many=True) return Response(serializer.data) else: return Response([]) -
Setting up Sentry with Django
I installed Sentry with docker-compose And I set up Django according to this manual https://docs.sentry.io/clients/python/integrations/django/ But errors do not come in Sentry I tested it: python manage.py raven test and got this result: DEBUG 2017-12-26 08:49:51,033 base 67 140371587118848 Configuring Raven for host: Client configuration: base_url : http://adyy.ru:9000/sentry project : 2 public_key : 946327fca2844e8684d8233c89826062 secret_key : 96fb7bee962c413ba7356434c84985b1 Sending a test message... DEBUG 2017-12-26 08:49:51,305 base 67 140371587118848 Sending message of length 3464 to http://adyy.ru:9000/sentry/api/2/store/ Event ID was '28ca8194b1904081938fc2189cc3b7d2' ERROR 2017-12-26 08:49:51,325 base 67 140371430176512 Sentry responded with an error: HTTP Error 403: OK (url: http://adyy.ru:9000/sentry/api/2/store/) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/raven/transport/threaded.py", line 165, in send_sync super(ThreadedHTTPTransport, self).send(url, data, headers) File "/usr/local/lib/python2.7/dist-packages/raven/transport/http.py", line 43, in send ca_certs=self.ca_certs, File "/usr/local/lib/python2.7/dist-packages/raven/utils/http.py", line 66, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python2.7/urllib2.py", line 437, in open response = meth(req, response) File "/usr/lib/python2.7/urllib2.py", line 550, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.7/urllib2.py", line 475, in error return self._call_chain(*args) File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 558, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: OK ERROR 2017-12-26 08:49:51,326 base 67 140371430176512 [u'This is a test message generated using ``raven test``'] what to … -
Call Rest API with user using Python requests
I want to call an API using requests.get() method where I have to give username and password as authentication like below. response = requests.get(url, auth=requests.auth.HTTPBasicAuth('username', 'password')) but I don't want to give password in auth as it will work dynamically where password will be encrypted. so is there any way to do this by only giving username and not password? -
Django error - 'function' object has no attribute 'MyForm'
I am new to Django and was working with Django forms and stuck at an error for which I am not finding any relevant solution. My Form.py is : from django import forms class MyForm(forms.Form): name = forms.CharField() email = forms.EmailField() text = forms.CharField(widget=forms.Textarea) and My views.py is : from django.shortcuts import render from django.http import HttpResponse from . import forms # Create your views here. def index(request): return render(request, 'basicapp/index.html') def forms(request): form = forms.MyForm() return render(request, 'basicapp/forms.html', context = { 'form' : form }) All the routing is Fine as I have checked by replacing forms with a normal HttpResponse but there is some problem in the forms.py or views.py as they the form in not being displayed in the browser and the Error is coming 'function' object has no attribute 'MyForm' Please Someone help :( I gotta move Forward -
TypeError: not enough arguments for format string python mysql
I want to collect each people's grade in the special subject of course with python. I get each person's grade one by one. For this reason, I write a SQL code like below. row come from easrlier sql result and it prints subject and course and it shows like ('CS', '201') categoriesWithFeedback contains unique nickname. I write sql code but it cannot understand row contains 2 parameter I think. sqlgrade = "SELECT `grade` FROM `enrolledtable` WHERE `subject`=%s and `course`=%s and `nickname`=%s" IE_students.append(categoriesWithFeedback) cursor.execute(sqlgrade, (row, categoriesWithFeedback)) IEaveragegrades += cursor.fetchone() ` Python ERROR is that Traceback (most recent call last): File "C:\wamp\www\MLWebsite\website\new.py", line 85, in cursor.execute(sqlgrade, (row, categoriesWithFeedback)) File "C:\Python27\Lib\site-packages\pymysql\cursors.py", line 163, in execute query = self.mogrify(query, args) File "C:\Python27\Lib\site-packages\pymysql\cursors.py", line 142, in mogrify query = query % self._escape_args(args, conn) TypeError: not enough arguments for format string Can anyone help me to solve that error? I don't want to use sqlparse if there is any solution without that. -
How to to run a python script using a button! (Using Django)?
I am a django newbie! I want to know how to run a python script on pressing a button using django! The script does return any value but it does some changes to a test account on a server(Google Ad Words Test Account). The script is ready! It would be really appreciated if someone could help me out! -
Change the template option based on the condition
How to change the template tag based on another template tag. task_count = {1 :3, 2: 0, 3: 1} --- i manually created task_type = {1:rebuild,2:upgrade,3:provisioning} ---- this from table I want to get the task count for ex: if the task id 1 then "Rebuild:3". I tried the below code it's not working {% for task in TaskTypeTag %} {{task_count.{{task.id}}}} -
add django csrf token to angular 5 form
im working on django-angular5 project i have a login form in angular how should i add csrf token to my form ? without what i get this error i searched same topic but people are using angular js that will not help me (i ng build angular app and im using static files) Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. it is my simple form for login in home.compoenent.html <form method="post"> <div class="input-field col s6"> <input id="first_name" type="text" name="username" class="validate"> <label for="first_name">نام کاربری</label> </div> <div class="input-field col s6"> <input id="first_name" type="password" name="password" class="validate"> <label for="first_name">کلمه عبور</label> </div> <input type="submit" class="waves-effect waves-light btn" value="login"/> <input type="hidden" name="next" value="{{ next }}"/> </form> -
Django LDAP authentication to another webpage
My company has a single common LDAP server for every web based products. I am developing an Django web product called myapp, which load some data/iframe from another web product called another_app. When user log in to myapp , they also need to open a new tag and log in to another_app, in order to be able to view some graph data loaded from another_app. It bring a little inconvenience I dont have any information about how another_app implemented , except confirm that, both myapp and another_app use the aforementioned LDAP server for their authentication. So question is: Any mechanism allow whenever user login to myapp, they also login to another_app . As mentioned , I developing myapp using Django/LDAP. Thanks -
Django : Heroku App crashed" method=GET path="/robots.txt
My app works fine on localhost but whenever i push it to heroku it gives the error below and app crashes -
django project not recognizing apps even though in installed_apps
I just upgraded my project from django 1.8 to 2.0 and now my project isn't recognizing the apps, templates, template tags, or anything to do with my apps. Any ideas? -
Jinja2 filters for dynamic registered templates
I've got the following code: from app.utils.logic.template_filters import get_date_europe env = Environment( loader=FileSystemLoader(template_dirs), autoescape=True, extensions=['jinja2.ext.i18n'], ) env.install_null_translations() env.filters['get_date_europe'] = get_date_europe def render_from_text(text, **context): t = jinja2.Template(text) return t.render(**context) and I want to add a custom filter to perform specific datetime formatting. text is a valid template stored as string. The problem is that when line {{ some_object.created_at|get_date_europe }} is included into template, jinja throws an exception jinja2.exceptions.TemplateAssertionError: no filter named 'get_date_europe' I set a debug breakpoint into first line of render_from_text and called env.filters, function appears to be there 'get_date_europe': <function get_date_europe at 0x10fca02f0>,. How can I make my filter visible to jinja? P.S. Django 1.9 is used. -
Not able to retrieve selected values from Django's Choicefield Form
Following is my Django form class Country(forms.Form): name = forms.CharField() country = forms.ChoiceField(widget=forms.Select(attrs={'id':'country'})) Following is code before sending form to a HTML page form = Country() choices = [('a', 'India'), ('b', 'United States of America')] form.fields['country'].choices = choices form.fields['country'].initial = 'b' return render(request,"Test.html",{"form":form}) Form is rendered properly in the front end and initial value is also set. When user clicks submit button. It is throwing exception. Following is the code i have written when user clicks submit button, f = Country(request.POST) print (f) print("Country Selected: " + f.cleaned_data['country']) I am getting the form like below when i printed the form after user submitted. <tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" value="ggg" id="id_name" required /></td></tr> <tr><th><label for="country">Country:</label></th><td><ul class="errorlist"><li>Select a valid choice. a is not one of the available choices.</li></ul><select name="country" id="country"> </select></td></tr> Please help me with this. Thanks! -
Pass hidden input along with a form on a Bootstrap 3 modal
Goal: I have a button that toggles Bootstrap 3 modal. The modal has a Django form on it. I want to pass an id along with the form when it is submitted (so that I can query DB with the id and save the cleaned data into an according row). Problem: I have everything working except submitting an id with the form. My approach was to create a hidden input element on the modal, but (a) I'm not sure if it's a feasible way and (b) the way my code is now, input element isn't being added. Code: To get straight to the point, I'm omitting views.py. Just assume id and form below are Python variables passed to the templates. #button.html #bootstrap and jquery are included in the header <script src="http://malsup.github.com/jquery.form.js"></script> <button data-toggle="modal" class="btn btn-info btn-lg" href="/app/modal/" data-target="#modal{{ id }}">click</button> <div class="modal fade" id="modal{{ id }}"> <div class="modal-dialog modal-lg"> <div class="modal-content"> ... </div> After some research, I based my modal on this. #modal.html #nothing included in the header <div class="modal-dialog modal-lg"> <div class="modal-content"> <form id="form" method='post' action=''> <div class="modal-header"> ... </div> <div class="modal-body"> {% csrf_token %} {{ form.as_table }} </div> <div class="modal-footer"> <input type="submit" id="btn" value="submit"/> </div> </form> <script> document.getElementById(btn).onclick … -
how to connect to my localhost server to run a django application?
i'm studying Django and now can't connect to my localhost server to run my projects even when i'm trying to run the browser on my local IP. help please -
How to implement "Drag and Drop" functionality in django-mptt?
I use django-mptt application in my project. This application allows users drag and drop tree nodes in admin page (DraggableMPTTAdmin). Is it possible to make the same functionality in custom template (not in admin)? P.S. I tried to use jsTree plugin in frontend. This plugin allows the user drag and drop nodes of the tree but jsTree has heavy API. Also I dont know how to save new structure of new tree cause jsTree render strange attributes in html for tree nodes. template: <ul class="root"> {% recursetree nodes %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> -
django-ses setting error : Module "django_ses" does not define a "SESBackend" attribute/class
I'm trying to send email using django-ses library and Amazon ses. I did all essential settings following this(https://github.com/django-ses/django-ses, installing boto and django-ses, insult AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and EMAIL_BACKEND = 'django_ses.SESBackend' in my settings.py) but when I tried to send email. I've got an error. ImportError: Module "django_ses" does not define a "SESBackend" attribute/class Is there any bugs in this django-ses library, or am I doing wrong something? I'm using windows 10, python3, and django 1.11