Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use model's serializer fields content?
I have a serializer like this: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email') and a function like this: def check (self , request): if unique('username' , 'email'): return True return False how could I pass 'username' and 'email' content through the function? -
Difference between child model types in Django
I am building a control panel that will have multiple sub-applications in Django. One of my models is an application, which will have important settings like name, description, install_path and id (so that I can associate specific settings and configuration values to this application. Right now I'm struggling in trying to figure out how to declare this particular model. Each application will do something completely different than each other application. One might manage specific CMS settings and another may handle password resets for our development environment. The goal is to get the commonly used things in one place. My question is, what is the difference between declaring my applications using abstract base class models vs. proxy models. The main information for each application will be the same. Each will have a name, description, etc. The difference will be what they do and what settings they use. The settings are in their own model though, with a link back to the application via foreign key. -
import error rest_framework_httpsignature.authentication django rest frame work?
i am importing from rest_framework_httpsignature.authentication import SignatureAuthentication in django 1.8v and python 2.7.6 ,it causeing importing error only to this class SignatureAuthentication in vs studio , please help but i can able to import this class rest_framework.authentication -
Lightweight alternative to geodjango for MVP (minimal viable product)
For a django-based webapp MVP I need a global city/country database. It has two requirements. It should be as simple as possible to get up and running. Ideally without much installation, but maybe as initial data in fixtures, which can be pushed to collaborators. The user generated location information (eg their home city), should later on be transferable to a more involved geodatabase like geodjango. Do you know a good option? Thank you! -
Creating answer related questions
this is my third post about the tool I am writing and until now you have helped me so much. I am writing a QuizTool which has to handle Polls, Multiple Choice Questions and Branched Questions. So far I am able to list my surveys, loop through questions and post the related answers to save them in my model. Also i am able to create multiselect fields for the Multiple Choice Questions. But its realy hard to figure out how the Branched Questions work for me. Let me explain how I approach to this problem. Here is the relevant part of my model: class Answer(models.Model): answer_id = models.AutoField(blank=False, null=False, primary_key=True) answer_text = models.CharField(blank=False, null=True, max_length=500, verbose_name=_(u'Text der Antwort')) # Internal fields date_created = models.DateTimeField(blank=False, null=True, auto_now_add=True, verbose_name=_(u'Erstellt am')) date_updated = models.DateTimeField(blank=True, null=True, auto_now=True, verbose_name=_(u'Geändert am')) def __str__(self): return self.answer_text class Meta: # db_table = 'data' verbose_name = _(u'Antwort') verbose_name_plural = _(u'Antworten') ordering = ['answer_id'] class Question(models.Model): question_id = models.AutoField(blank=False, null=False, primary_key=True) # Fields answer = models.ManyToManyField('Answer', through='Question_Answer', related_name='+') question_text = models.CharField(blank=False, null=True, max_length=500, verbose_name=_(u'Text der Frage')) # Internal fields date_created = models.DateTimeField(blank=False, null=True, auto_now_add=True, verbose_name=_(u'Erstellt am')) date_updated = models.DateTimeField(blank=True, null=True, auto_now=True, verbose_name=_(u'Geändert am')) #Typunterscheidung der Fragen QUESTION_TYPES = ( ('0', … -
Centralized Authentication in Django 2.0
I need some help with building something (That I call) Centralized Authentication Server in Django 2.0, which will support the following: Say There are 2 services: Service A - which is the frontend application. It's a simple Django project the has only one view that serves a VueJS application. Service B - which is the API. Service A is sending AJAX requests to Service B. The 2 services are totally separate, and ideally I would like to not handle any User model in none of the services. What I would like is to use Service C, which is a service that handles all the Authentication and the User model. When a user goes to Service A and he is not logged in, he will be redirected to Service C and login to the system using his credentials (User/Password) and then will be redirected back to Service A, alongside with a token that will enable him to speak with service B. Then service B will get this token, and authenticate it against service C. (In each request, or only in the first request / dedicated 'login' request). I read a lot about django-mama-cas + django-cas-ng, and tried to implement it. But … -
Anonymise email data with django allauth
I am migrating an old database to django allauth using the email address as the username. However, the database has a load of old users that have used the same email address to register for separate accounts, so the migration is failing. I'd quite like to anonymise the duplicate accounts (and it's something I think is worth being able to do anyway, with GDPR in mind) but I'm not sure how to go about it. The only thing I can think of is to set their email address to something (unique) that my system can then check for and not send emails to. But that feels really hacky to me. Is there a better way? -
Heroku django program deployed,but returned a 400 error
The thing is,I wrote a very simple django blog.And I put it on Github.Then I tried to deploy it on Heroku.When I finished it,I only saw 400 Bad Request.I'm confused.The log is here: 2018-03-13T11:56:51.929117+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=guoguoblog.herokuapp.com request_id=85b467df-9cd5-4bae-8cd8-e33a9c89d1a9 fwd="112.9.115.29" dyno=web.1 connect=1ms service=20ms status=400 bytes=154 protocol=https 2018-03-13T11:56:51.928540+00:00 app[web.1]: [13/Mar/2018 19:56:51] "GET /favicon.ico HTTP/1.1" 400 26 And repeat again when I flush my page. What can I do? Oh,this is my github project.https://github.com/qwedc001/DjangoBlog Can anybody help me? Eric -
building big xml file with python 2
im trying to get the best performance to build a big XML file in python 2/django. the XML file produced have ~500mb and the 1st approach used was with lxml. took over 3H30. then i tested with xml.sax and took over the same time, 3h30. im trying to find the fastest way and with less memory consumption. i searched over several days and the best ways i found were these two, but then i found that lxml have xml.sax implementation aswell. any ideas to help? thanks! -
What is the best way to manage permissions for user and multiple admin for object instances for a web application
I am looking for best way for my web application. It has many admin and users. the workflow is like there is super admin who create account for company admin (this can be many or one). the company admin can have many end user's who access departments of that company. the company admin set or remove permission for end user like user1 can access dept but not dept2. So what would be the best structure/design to build this system. (I am going to use django for this) -
Bootstrap modal dialog dismiss not working but submit button
I have a problem which I seam to find no answer to. I have modal which contains a form for submitting data to the server. The submitting part is working just fine. All data gets send and the server takes the correct steps. However, the buttons to close/dismiss the modal do not work. The form gets pulled by ajax request from the server and is embedded in the current page <!-- Dialog for user input of forms--> <div id="form-modal" class="modal fade" role="dialog"> </div> Ajax pulled form <div class="modal-dialog" role="document"> <!-- Content of dialog --> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Datensatz erstellen</h4> <button type="button" class="close" data-dismiss="modal">&times </button> </div> <div class="modal-body"> <form action="{% url 'knowledgeedit' %}" method="POST" id=""> {% csrf_token %} {% for field in form %} <div id="{{ field.auto_id }}_container"> {{ field.help_text }} <div> {{ field.label_tag }} {{ field }} </div> {% endfor %} </div> </form> <div class="modal-footer"> <button class="btn btn-success" type="submit" name="{{ requestedForm }}">Speichern</button> <button class="btn btn-default" type="button" data-dismiss="modal">Abbrechen</button> </div> </div> </div> </div> css: body { font-family: 'Open Sans', serif; padding-top: 54px; color: #868e96; } .btn-primary{ background-color: #bd5d38 !important; border-color: #868e96 !important; } /* Sections */ @media (min-width:992px) { body { padding-top: 0; padding-left: 17rem; } }h1, h2,h3,h4, h5, h6 … -
Filtered records in django template
I am building a races app, where in a webpage I want to display records from the db, grouped based on the year a race took place and on the type of the race, so as to calculate some stats. Which is the best way to pass these groups of records in the template and build the methods for the calculation of the stats? a) Passing a dictionary through views? b) Applying a custom filter? c) Applying a simple tag? d) Building a custom Manager? e) Building the stats methods in models.py, and if so, how can I apply the group filters? f) any other way? Please, provide a working example if possible. -
How to iterate ElasticSearch data in Python/Django?
I have ElasticSearch iterated data like this: (Pdb) data[0] {'_index': 'publishserdata-index', '_type': 'publishser_data_index', '_id': '35', '_score': 1.0, '_source': {'publisher': 'Admin', 'department': 'IT', 'subdepartment': 'Full Stack Developer', 'inventory_ID': 'IT003', 'title': 'Why Should I Use Celery?', }} I want get publisher,department,title data. I tried data[0]._source try to user dict data[0].__dict__ but it's showing error. -
saving form - many to many relationship
I am trying to save form based data in many to many relationship. My models is as follow: class Student(models.Model): stuName = models.CharField(max_length=100) stuCity = models.CharField(max_length=100) stuPhone = models.IntegerField(max_length=10) stuNationality = models.CharField(max_length=50) stuCreatedt = models.DateTimeField(default=timezone.now) def __str__(self): return '%s %s %s' % (self.stuName,self.stuCity,self.stuNationality) class Dept(models.Model): deptId = models.AutoField(primary_key=True) deptName = models.CharField(max_length=100) def __str__(self): return '%s %s' % (self.deptId, self.deptName) class Course(models.Model): courseId = models.AutoField(primary_key=True) courseName = models.CharField(max_length=100) enrolledStu = models.IntegerField(max_length=3) students = models.ManyToManyField(Student) dept = models.ForeignKey(Dept, on_delete=models.CASCADE) def __str__(self): return '%s %s %s %s' % (self.courseName,self.enrolledStu,self.students,self.dept) which i am trying to save. my view is def addStudent(request): if request.method == "POST": form = CourseForm(request.POST) if form.is_valid(): print(form.cleaned_data) course = form.save(commit=False) course.courseName = request.courseName course.save() form.save_m2m() return redirect('lstDetail') i tried without form.save_m2m() method but still its giving error. AttributeError at /stuApp/new/ 'WSGIRequest' object has no attribute 'courseName' Request Method: POST Request URL: http://127.0.0.1:8000/stuApp/new/ Django Version: 1.11.10 Exception Type: AttributeError Exception Value: WSGIRequest' object has no attribute 'courseName Exception Location: C:\Users\PycharmProjects\learning\stuApp\views.py in addStudent, line 22 Python Executable: C:\Users\PycharmProjects\learning\venv\Scripts\python.exe Python Version: 3.6.4 this is from html page. on console there isn't any error its just prints the query. basically i am unable to save data with many to many fields and relationship. my … -
Django save previous object from models
In a Django admin site, I have this class. I want to save a previous version of a object (Servers) which is a manytomany field to find changes on the object. With normal CharField this work, but for manytomany fields I got this error: "<SourceDestinationGroup: asdas>" needs to have a value for field "id" before this many-to-many relationship can be used. here is my objectclass class SourceDestinationGroup(models.Model): STATE_CHOICES = ( ('C', 'in Change'), ('F', 'Finished') ) ServerGroupName = models.CharField(max_length=256) Description = models.CharField(max_length=256,blank=True) Servers = models.ManyToManyField(Server) Status = models.CharField(max_length=1, choices=STATE_CHOICES, default='C') def __init__(self, *args, **kw): super(SourceDestinationGroup, self).__init__(*args, **kw) self._old_Servers = self.Servers def save(self, **kw): if self.Servers != self._old_Servers: self.Status = 'C' self._old_Servers = self.Servers super(SourceDestinationGroup, self).save(**kw) def __str__(self): return self.ServerGroupName -
Django forms validation is not showing up in the template
My problem is, when I validate forms for errors, some text with warning would show up, But id does not. I was searching for 2 days for some good answers and i tried also everything, so I thing that is some really silly mistake. Can anyone help me with this problem? I was trying to implement validation in my register subpage so.... First image is my model.py for registration Second image is my inputForms.py with simple validation Third image is my view.py And fourth is my template.html for registration Someone please help me with this mistake. Thank you very much. -
how to dispatch a specific method with csrf_exempt in django class based view
Hello i am trying to set csrf_exempt on class based view in django i've tried this one now my class is look like this: class UserView(View): # Check csrf here def get(self, request, pk): #code here # I want to exempt csrf checking only on this method def post(self, request): #code here Meanwhile if I use @method_decorator(csrf_exempt, name='dispatch') it will applied to every methods in the class. What's the best approach to exempt only for specific method in a class based view in Django? -
Django celery for download large file
I am developing a django app and my app need to user to upload the urls in excel files. On server side i am reading the excel file by each cells, extracting the news article of the urls and generating the summary of article. This process can take up to 5-10 minutes for the long list of urls. I am using celery for managing the long running task but somehow server is giving me error 500 - Internal server error after 2 min without completing the task __init__.py from .celery import app as celery_app __all__ = ['celery_app'] Setting.py BROKER_URL = 'django://' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery_app.py from __future__ import absolute_import import os import django from celery import Celery from django.conf import settings from kombu import serialization serialization.registry._decoders.pop("application/x-python-serialize") os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'news.settings') django.setup() app = Celery('news') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) summary.py from celery import shared_task @shared_task def WritesummaryfromArticleToExcel(input_file,noofline,lang): try: data=False wb = xlrd.open_workbook(file_contents=input_file.read()) wb_sheet=wb.sheet_by_index(0) df=pd.DataFrame(columns=['Full Article','Summary']) for rownum in range(0, wb_sheet.nrows): # for colnum in range(0,1): try: rw=wb_sheet.cell_value(rownum,0) if type(rw)==float or type(rw)==int: rw= str(rw) # if len(rw)>15000: data=True articletext=rw # nooflines=request.data["numberofline"] lantext="" lantexttemp= articletext.split('\n')[0:2] for l in lantexttemp: lantext=lantext +"\n" +l lan=detect(lantext) view.py def translatedoc(request): data="" convrowstr="" if request.method=='POST': … -
djang template loop for with ajax script multiply
I've been following with "Django by example' practice book doing like unlike system. I encountered some problem with Ajax script when I a nested then into an loop for ( "for post in posts iterating view"). When I put into my template’s loop, this ajax I get looping likes in all iterated post. Do You have any tips how can I tackle with this ? enter code here <script> var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.each(document).ready(function(){ $('a.like').click(function(e){ e.preventDefault(); $.post('{% url "like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); // toggle data-action $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); // toggle link text $('a.like').text(previous_action == 'like' ? 'Unlike' : 'Like'); // update total likes var previous_likes = parseInt($('span.count .total'). text()); $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1); } } ); }); }); </script> enter code here {% for post in posts %} <small>Posts: {{ post.message}}</small> {% include 'posts/like.html' %} {% endfor%} -
Access the Django-Rest-Framework url do not load the styles file
I have a project with the settings.py: # -*- coding: utf-8 -*- """ Django settings for Qiyun02 project. Generated by 'django-admin startproject' using Django 1.11.5. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os import sys #import django.contrib.auth.middleware # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PARENT_DIR = os.path.abspath(os.path.join(BASE_DIR, os.pardir)) # 增加sys目录 sys.path.insert(0, BASE_DIR) sys.path.insert(0, os.path.join(PARENT_DIR,'旗云管理员后台')) sys.path.insert(0, os.path.join(PARENT_DIR,'用户前台')) sys.path.insert(0, os.path.join(PARENT_DIR,'用户管理后台')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'u8ctyimjuy7t-7r3%$&4sc2g^5fhc8dathp8z&(7pp=&eee@zn' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_docs', # API文档 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', ...... ] SITE_ID = 1 # email backend TODO 这个,每个商户可以自己定义邮箱 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' #EMAIL_USE_TLS = True EMAIL_USE_SSL = True EMAIL_HOST = 'smtp.gmail.com' # QQ:smtp.qq.com 163:smtp.163.com EMAIL_PORT = 465 EMAIL_HOST_USER = 'qiyunserver@gmail.com' EMAIL_HOST_PASSWORD = 'qiyunserver123' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER # TODO 方便调试,关闭Token验证 REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES':[], #'rest_framework.permissions.IsAuthenticated' 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), #['rest_framework.authentication.TokenAuthentication'], # 'rest_framework.authentication.TokenAuthentication' #'DEFAULT_PAGINATION_CLASS': ('rest_framework.pagination.PageNumberPagination',), 不能打开这个 #'PAGE_SIZE':10, … -
payment via PayPal payout API
I am using Payout API (in Django) for PayPal mass payments . How can i make all these payments as "PERSONAL" from api . Code snippet of PayPal object that i am using : payout = Payout({ "sender_batch_header": { "sender_batch_id": batch_id, "email_subject": mail['subject'] }, "items": [ { "recipient_type": "EMAIL", "amount": { "value": amount, "currency": "USD" }, "receiver": receiver_email, "note": mail['body'] "sender_item_id": id } ] }) Reference : https://developer.paypal.com/docs/api/payments.payouts-batch/#payouts . Is there any Key value that needs to be sent with the above object or is there any different approach for PERSONAL payment from PayPal API. -
None type error in Django rest RegisterView
I am using Django RestFramework's RegisterView for the registration api in my project.I use a custom adapter as well, it is as follows. class CustomAccountAdapter(DefaultAccountAdapter): """ Override all_auth's default adapter """ def send_confirmation_mail(self, request, emailconfirmation, signup): # current_site = get_current_site(request) promo_code = emailconfirmation.email_address.user.promo_code activate_url = "%s/#/verifyEmail/%s/" % ( settings.FRONTEND_HOSTNAME, emailconfirmation.key ) if promo_code: activate_url = "%s/#/verifyEmail/%s/?promo_code=%s" % ( settings.FRONTEND_HOSTNAME, emailconfirmation.key, promo_code ) ctx = { "user": emailconfirmation.email_address.user, "activate_url": activate_url, "current_site": settings.FRONTEND_HOSTNAME } if signup: email_template = 'account/email/email_confirmation_signup' else: email_template = 'account/email/email_confirmation' self.send_mail(email_template, emailconfirmation.email_address.email, ctx) I get an error while the sending the confirmation mail to the newly registered user.The error is below File "/home/ubuntu/fizprod_env/local/lib/python2.7/site-packages/django/core/mail/message.py", line 283, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/ubuntu/fizprod_env/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 99, in send_messages sent = self._send(message) File "/home/ubuntu/fizprod_env/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 110, in _send from_email = sanitize_address(email_message.from_email, email_message.encoding) File "/home/ubuntu/fizprod_env/local/lib/python2.7/site-packages/django/core/mail/message.py", line 105, in sanitize_address nm, addr = addr TypeError: 'NoneType' object is not iterable Can anyone tell me what is the error and how it's happening.I use Django 1.7, python 2.7, Django REST 3.1.1 -
Is it possible to add a custom attribute to a model field?
Here's my model: def Post(models.Model): ... video = models.BooleanField(default=False, youtube=False) is it possible to add the youtube attribute so I can use it in my template like so: {% if video.youtube %} <p>text</p> {% endif %} -
Django: raw passwords via request.POST
This question concerns the standard UserCreationForm within Django, and the way that passwords are stored, extracted and used through a request object. Specifically the fact that I seem to be able to print raw passwords through print(request.POST). File contents will be provided at the end of this post. I have created a registration page. I have set up a very basic class-based view that authenticates and logs the newly created user in. The actual HTML of that page is rendered automatically in this case, through {{ form.as_p }} where form is an instance of UserCreationForm. How come, when I execute print(request.POST), I get something along the lines of this returned: <QueryDict: {'csrfmiddlewaretoken': ['keeping_this_private'], 'username': ['William'], 'password1': ['ACTUALPASSWORD'], 'password2': ['ACTUALPASSWORD'], 'button': ['']}> Is this really secure? As I have only been programming for a couple of months, I am still learning. Views.py: class RegisterView(View): def get(self, request): form = UserCreationForm() return render(request, 'authentication/registration.html', {'form': form}) def post(self, request): form = UserCreationForm(request.POST) if form.is_valid(): print(request.POST) form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: return render(request, 'authentication/registration.html', {'form': form}) Registration.html {% extends 'base.html' %} {% block body %} <body class="text-center"> <form method="post"> {% csrf_token %} … -
Django 2.0 + Postgres heroku migrations
I am trying to run a Django application with Postgres in Heroku. I have created an app for the application but the problem is that the app migrations are not being applied in Heroku. I am using the heroku starter base template and have committed the necessary migration files. When I run heroku run python manage.py migrate, the first set of migrations apply: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK blah blah blah But when I run it the second time it gives me the the output Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. If I specify the app using heroku run python manage.py migrate phone I get the error CommandError: No migrations present for: phone In my local development, I have an app called phone that I have added to the settings.py and can run local migrations.