Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django urls -Reverse for 'url name' not found
I have a Django application called polls. I'm trying to use a form in a template that it's action is calling to another url. mysite/urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^$', include('polls.urls')), url(r'^admin/', admin.site.urls), ] polls/urls.py: from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url(r'^$', views.call_login, name='call_login'), url(r'^homepage/$', views.login, name='login'), ] login.html: <form name="form" method="post" action="{% url 'login' %}" > {% csrf_token %} <input type="text" placeholder="username" name="user"><br> <input type="password" placeholder="password" name="password"><br> <input type="submit" value="Login" /> </form> The error I got: NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Any idea why? -
One view fo multiple urls to handle multiple languages in django
I would like to use the same views for different supported languages. For exemple I have the default language and the english. In my main urls: url(r'^posts/', include('posts.urls')), #for default language url(r'^en/posts/', include('posts.urls')), #for english The urls file of my posts app is like this: url(r'^newpost/$', views.PostFormView.as_view(), name='add'), url(r'^favorite/$', views.favorite, name='favorite'), so, for example, both www.mysite.com/posts/add and www.mysite.com/en/posts/add send to the same view PostFormView and according to the url if it contains "/en/" or not I send the content in the right language. However, the issue is with the redirect or revers sends always to the default language. For example 'posts:add' sends always to "www.mysite.com/posts/add" because I have url(r'^posts/', include('posts.urls')) before url(r'^en/posts/', include('posts.urls')) are there any ways to use the same view for two different urls. Or, how can I handle multiple languages website? Do we have to duplicate all the apps for all the supported languages? -
Django- Paypal integration issue
Django - Paypal integration issue on credit card checkout... How do I make auto-fill credit card details in new express checkout for PayPal payments. I have to integrate it with Django Donate App. Please don't suggest this :- https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECCustomizing/#automatically-fill-out-shipping-and-contact-information. This was deprecated from January. -
Django rest framework custom return response
So i have this custom register api which register a user, but when user successfully register, i want it to have this message "You have successfully register an account!" But i tried different method but get an error instead. serializer.py class UserCreate2Serializer(ModelSerializer): email = EmailField(label='Email Address') valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p'] birthTime = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True, required=False) class Meta: model = MyUser fields = ['username', 'password', 'email', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'birthTime'] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): # to validate if the user have been used email = data['email'] user_queryset = MyUser.objects.filter(email=email) if user_queryset.exists(): raise ValidationError("This user has already registered.") return data def create(self, validated_data): username = validated_data['username'] password = validated_data['password'] email = validated_data['email'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] gender = validated_data['gender'] nric = validated_data['nric'] birthday = validated_data['birthday'] birthTime = validated_data['birthTime'] user_obj = MyUser( username = username, email = email, first_name = first_name, last_name = last_name, gender = gender, nric = nric, birthday = birthday, birthTime = birthTime, ) user_obj.set_password(password) user_obj.save() return validated views.py class CreateUser2View(CreateAPIView): permission_classes = [AllowAny] serializer_class = UserCreate2Serializer queryset = MyUser.objects.all() i tried changing this into the serializer user_obj.set_password(password) user_obj.save() content = {'Message' : 'You have successfully register an … -
PrimaryKeyRelatedField(source='order.market', read_only=True) gives an AttributeError
models.py class ClientTransaction(model.Models): order = models.ForeignKey('main.Order', related_name='client_transaction', on_delete=models.PROTECT, null=True) class Order(BaseModel): market = models.ForeignKey('main.Market', on_delete=models.PROTECT, related_name='order') serializers.py class ClientTransactionSerializer(ModelSerializer): market = serializers.PrimaryKeyRelatedField(source='order.market', read_only=True) class Meta: model = ClientTransaction fields=['market'] Giving an error: AttributeError: 'NoneType' object has no attribute 'market' django==2, djangorestframework=>3.7.1 full error image