Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to catch single quote symbol (') into string for JSON.parse?
I get a lot of data from Django into template as: var dataFromServer = JSON.parse('{{ delivery_provider|jsonify }}'); Anytime when into Django data presents some symbols ' like this {"id": 1, "company_name": "User's company", "address": null } my javascript code is crashed with error Uncaught SyntaxError: missing ) after argument list because symbol ' have wrong interpretation into string at front side. How to escape this quote symbols by Python/Django? Or, is exists some solution at the front side? -
Getting django next post and previous post?
I would like to add the previous post and the next post feature to the blog page, it works fine, but it does not work when I add active passive features to blogs. here is my view.py model = Blog queryset = Blog.objects.filter(is_active__exact=True) template_name = 'site/Blog/post.html' pk_url_kwarg = "id" slug_url_kwarg = 'slug' slug_field = 'slug_tr' query_pk_and_slug = True def get_context_data(self, **kwargs): context = super(BlogDetailView, self).get_context_data(**kwargs) recent_posts = Blog.objects.all().order_by('-created_at')[:3] comments = BlogComment.objects.filter(target_blog__exact=self.object) previous_post = Blog.objects.filter(is_active=True).filter(created_at__lt=self.object.created_at).order_by('-created_at')[:1] next_post_c = Blog.objects.filter(is_active=True).filter(created_at__gt=self.object.created_at).order_by('-created_at')[:1] How can ı fix this problem? -
django - how to add ForeignKey's ForeignKey (3 level) field to the form
I'm trying to make an inventory system with 4 models - Category, ProductGroup, Product, Stock - as given below. class Category(MPTTModel): name=models.CharField(max_length=75,null=False,blank=False, unique=True) parent=TreeForeignKey('self', null=True, blank=True, related_name='children') class ProductGroup(models.Model): name = models.CharField(max_length=30,null=False, blank=False) category=TreeForeignKey('category.Category', null=False,blank=False) class Product(models.Model): product_group=models.ForeignKey('productgroup.ProductGroup', null=False,blank=False) manufacturer=models.ForeignKey(Manufacturer, null=False,blank=False) product_type=models.CharField(max_length=2, choices=PRODUCT_TYPE,) opening_stock=models.PositiveIntegerField(default=0) TRANSACTION_TYPE=(('I','Stock In'),('O','Stock Out')) class Stock(models.Model): product=models.ForeignKey('product.Product', blank=False,null=False) quantity=models.PositiveIntegerField(blank=False, null=False) ttype=models.CharField(max_length=1,verbose_name="Transaction type",choices=TRANSACTION_TYPE, blank=False) and I have a model form for recording Stock-In/Out as follows. class StockInOutForm(forms.ModelForm): class Meta: model = Stock fields=['product','quantity','date'] (and two separate views for StockIn and StockOut to set ttype) Since the table products is basically a permutation of ProductGroup,Manufacturer and ProductType it will contain a huge set of records. I need to add the Cateogry and ProductGroup fields as chained fields so that the for Product.name in the form would contain only a filtered set. Kindly give some insights on how to proceed. Thanks. -
Django Factory Boy - Reverse dependencies (reverse ForeignKey) common recipy
I am new to FactoryBoy. I am trying the example for the exact example in the docs: reverse dependencies . 1) Is it correct that the "UserLogFactory" mentioned is "so obvious" one should make it oneself as in: class UserLogFactory(factory.django.DjangoModelFactory): class Meta: model = models.UserLog 2) I am getting an attributeError: AttributeError: type object 'UserLog' has no attribute 'ACTION_CREATE' I searched the internet, I found 1 reference (github error report) who seemed to have solved it himself the same day. He did not mention the solution, but from his comments I gather it is something obvious... Thanks in advance for the help! Kind regards. -
Twitter login in Django without using any 3rd party library for Twitter integration
I need a code for twitter login in an application I am writing in Django python, which does not use any 3rd party library like Django-SocialAuth or django-twitterauth for a project. Using a third party library will makes things easier but that is one requirement for the project I am doing. Thank you. -
Django: How to limit model access permission to its owner?
I have a django model and and i want that model to be accessed only by its owner(user who created the model). So i created a permission class as follows class IsOwnerOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Write permissions are only allowed to the owner of the snippet. return obj.owner == request.user and applied this permission on modelviewset class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer permission_classes = (IsOwnerOnly,) def perform_create(self, serializer): serializer.save(owner=self.request.user) But even then every authenticated user can access the whole list of items. So how could i limit the item access to only its owner? I have included Tokenauthentication in settings page as shown REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), } -
Django remove instance from m2m
I am now testing on my database schema. My ORM is django==1.10.6 Requirements: customer can has multiple license_plates And license_plate can belongs to multiple customers For example: One family has 5 men they are dad, mom, son, and daughter. Suppose this family has 2 cars. Therefore m2m is the way to go Problem: Django ORM seems to not remove the instance relation in the LicensePlateCustomerInformation manager cust_info.license_plates.count() returns 2 Therefore this line will be failed assert 1 == cust_info.license_plates.count() tests.py class CustomerInformationAPITestCase(APITestCase): def setUp(self): self.dealer = mommy.make(Dealer, name='jjj') license_plate = mommy.make(LicensePlate) self.license_plate_id = license_plate.id self.user = User.objects.create_user(username='test', password='test') mommy.make(UserProfile, user=self.user) self.client.force_authenticate(self.user) self.data = { 'phone_number_1': 'number1', 'phone_number_2': '', 'address_line_1': '', 'address_line_2': '', 'prefecture': '', 'town': '', 'city': '', 'building': '', 'postal_code': '', 'location_position': None, 'is_imported': False, 'email_notification': CustomerInformation.UNKNOWN, 'letter_notification': CustomerInformation.UNKNOWN, 'storefront_notification': CustomerInformation.UNKNOWN, 'announcement_notification': CustomerInformation.UNKNOWN, 'family_name': 'Lars Hawkins', 'given_name': 'Reagan Ashley', 'email': 'hilacog@yahoo.com', 'profile_picture': None, 'dealer': self.dealer.id, 'license_plate_id': self.license_plate_id, 'license_plates': [] } self.full = { 'phone_number_1': '1234567890', 'phone_number_2': '0987654321', 'address_line_1': 'bkk', 'address_line_2': 'tokyo', 'prefecture': 'bkk', 'town': 'bkk', 'city': 'bkk', 'building': 'siam@siam building', 'postal_code': '10330', 'email_notification': CustomerInformation.UNKNOWN, 'letter_notification': CustomerInformation.UNKNOWN, 'storefront_notification': CustomerInformation.UNKNOWN, 'announcement_notification': CustomerInformation.UNKNOWN, 'family_name': 'Lars Hawkins', 'given_name': 'Reagan Ashley', 'email': 'hilacog@yahoo.com', 'dealer': self.dealer.id, 'license_plate_id': self.license_plate_id, } self.url = reverse_lazy('api:customer_info-list') Here is my … -
Real time display command line message on browser
I have ajax call on client side to ask server side call the subprocess to execute a matlab program.Now in my server side is doing this: def meta2db(request): if(request.method == "POST"): cur_status = status.objects.all() Dataset = cur_status[0].Dataset print(Dataset) is_multiclass = request.POST.get('multiclass', False) if(is_multiclass != 'on'): is_multiclass = 'false' require_mapper = request.POST.get('require_mapper', False) if(require_mapper == 'on'): mapper = request.POST.get('cls_mapper_pth', False) else: require_mapper= 'false' mapper = 'none' require_aspect_ratio = request.POST.get('require_aspect_ratio', False) if(require_aspect_ratio == 'on'): aspect_ratio = request.POST.get('aspect_ratio', False) else: require_aspect_ratio = 'false' aspect_ratio ='none' run_octave(Dataset,is_multiclass,require_mapper,mapper,require_aspect_ratio,aspect_ratio) return render(request, 'meta2db.html') def run_octave(dataset,is_multiclass,require_mapper,mapper,require_aspect_ratio,aspect_ratio): origWD = os.getcwd() args = ["octave", "dbEval.m",dataset,is_multiclass,require_mapper,\ mapper,require_aspect_ratio,aspect_ratio] os.chdir(os.path.join(os.path.abspath(sys.path[0]), "../scripts/")) process = subprocess.Popen(args, stdout=subprocess.PIPE) #print(os.listdir("../scripts/results/chruch_street/")) time.sleep(10) if process.poll() is None: process.kill() else: print(p.communicate()) for line in process.stdout: print(line) os.chdir(origWD) Now the problem is that I want to return the command line message which is for line in process.stdout: print(line) to client side and real time show the message to the brower. what strategy should i take? -
Using Djangos mail reset, how can I change the email account mailgun sends from
So ive set up my mailgun account and emails are being sent to the user, however they are being sent from the email webmaster@localhost. How can I change it to be admin@xyz.com? Here is the config for mailgun i have in my settings.py EMAIL_HOST = 'smtp.mailgun.org' EMAIL_PORT = 587 EMAIL_HOST_USER = 'postmaster@mg.lessonreview.net' EMAIL_HOST_PASSWORD = '62127479c6563773025184b28b113551' EMAIL_USE_TLS = True Thanks -
Unable to bind ajax data into pop up?
I am using Django and on pop up, I am displaying user detail I am getting data in the form of HTMLusing ajax and django but I am unable to bind the data into my popup. my view:- def app_user_by_id(request,user_id=None): if request.method == "GET": result_data_for_editing ={} master_user_types_list = MasterUserTypes.objects.using("cms").all() university_all_list = Universities.objects.using("cms").all() if request.method == "GET": get_user_api_url = userService['getUserDetail'] + str(user_id) response_data = create_get_request(get_user_api_url) if response_data.status_code == 200: print response_data.text json_data = json.loads(response_data.text) if json_data['data'] is not None: result_data_for_editing = json_data['data'] if request.is_ajax(): html = render_to_string('templates/app_user/user_by_id.html', {'result_data_for_editing': result_data_for_editing, 'master_user_types_list': master_user_types_list,'university_all_list':university_all_list,}) return HttpResponse(html) and the ajax call function:- $(document).ready(function () { $('.getObjectById').click(function () { if ($(this).attr('id') && $(this).attr('action')) { getObjectById(this); } else { alert("id and action is required field ...............") } }); }); function getObjectById(object) { var baseURL = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : ''); var requestData = {}; var id = object.getAttribute("id"); requestData.id = id; $.ajax({ url: baseURL+'/appuser/getUserDetailById/'+ id, method: 'GET', dataType: "json", contentType: "application/json", beforeSend: function () { }, success: function (data) { alert("hjwekhkwhekewh"); var div ='<div ' + '>' + data+ '</div>'; $("#usergetdetailfromapi").append(data); }, error: function (jqXHR, ex) { ajaxLoaderStop(); } }); } There is no problem with ajax call its … -
How to create my own django admin panel and NOT use a simple django admin panel
I want to write my own django admin and not use a simple default one -
Django + Docker + virtualenv + Heroku deployment
I would like to use Docker with my existing Django project in virtualenv and MySQL database. It seems to my that my solution is not optimal (BTW it is not working). My app is not finished, but I wonder if it is possible to deploy it on Heroku and working with it without publishing? I will be grateful if you could show me the best solution. To wit this is my docker-compose.yml: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" db: image: mysql environment: - MYSQL_ALLOW_EMPTY_PASSWORD=yes - MYSQL_USER=root - MYSQL_DATABASE=pri Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pri', 'USER': 'root', 'HOST': 'db', } } Structure of my files looks in this way: DockerContainerDirectory: - docker-compose.yml - Dockerfile - requirements.txt - ProjectDirectory In ProjectDirectory I have virtualenv and Project: - bin - include - lib - pip-selfcheck.json - Project In Project I have git repository, back-end and front-end written in Angular2: - backendFolder - frontendFolder backendFolder: -backendProject backendProject: - my project with `manage.py` etc. -
Django Rest Framework and angular 2 integration
My backend and frontend is running on different port. When i say my backend to add a csrf cookie It's adding the csrf on its own address which am not able to access from my client side code. I don't see much docs/samples for drf and angular 2. -
Django updating static files
Consider a scenario where my I have my website on a server. All the static files will be cached when the user request for the first time and I push some changes in static file and I need a method so that when users request for the next time after changing the static files new files should be cached for one time Thank you, -
How To Find Nearest Point From User Location using geodjango?
I am trying to find the nearest point using geodjango. I tried using the following code: LocationInfo.objects.filter(coordinates__distance_lte=(user_location, D(km=2))) But It only works if the location is within specified distance. But I need to find the point nearest to the user without using any limit during query. -
error saving decoded image to the model Django
I have a base-64 string that I sent to the routes views.py and the decode it back using the code image_data = request.POST.get('image_data') pattern = r'^data:(?P<mime_type>[^;]+);base64,(?P<image>.+)$' result = re.match(pattern, image_data) if result: mime_type = result.group('mime_type') image = result.group('image').decode('base64') saveImage = uploadImage(image=image, imageMime=mime_type) saveImage.save() Once decoded, I need to save it to the folder in the project and not locally. However when I call .save(), I get an encoding error: DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0x89 in position 0: invalid start byte. You passed in '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x. Do I need to strip of the PNG part for this to work? My model is as follows: class uploadImage(models.Model): image = models.ImageField(upload_to='Gallery') imageMime = models.CharField(max_length=50) -
Scrollable div with multiple tables
I have a div containing multiple tables with variable number of rows and i would need to make this thing scrollable. <div style="overflow-y: scroll;"> {% regroup documents by upload_time|date:" d F o" as documents_by_date %} {% for document in documents_by_date %} <table style="text-align: left; margin-top: 15px; width: 100%;"> <tr> <th width="70%">{{ document.grouper}}</th> <th align="center"> Uploaded by </th> </tr> {% for doc in document.list %} <tr> <td> <a href="{{ doc.docfile.url }}">{{ doc.filename }}</a> </td> <td align="center"> {{doc.upload_user}} </td> </tr> {% endfor %} {% endfor %} </table> </div> Right now this shows me a scrollbar but it doesnt work. I have almost no experience in html and css... -
Django, I want to take an input from a form and contents of the template should be according to the input
models.py class Transaction(models.Model): price = models.IntegerField(default=0) abc = models.IntegerField(default=0) pqr = models.IntegerField(default=0) ghi = models.IntegerField(default=0) Then I take a user input input.html <form method="POST" action="search/" style="margin-left:5em;"> {% csrf_token %} <input type="radio" name="account" value="price"> price<br> <input type="radio" name="account" value="abc"> abc<br> <input type="radio" name="account" value="pqr"> pqr<br> <input type="radio" name="account" value="ghi"> ghi<br> </form> views. py def search(request): if request.method == 'POST': search_id = request.POST.get("account", None) selected_transactions = Transaction.objects.exclude(search_id=0) return render(request, 'stats/account_details.html', {'selected_transactions': selected_transactions, 'search_id': search_id}) else: return render(request, 'stats/index.html') I have to display contents based on user input. account_details.html <table> <tr> <th>Transaction date</th> <th>{{ search_id }}</th> </tr> {% for transaction in selected_transactions %} <tr> <td>{{ transaction.created_date }}</td> <td>{{ transaction.{{ search_id }} }}</td> </tr> {% endfor %} </table> I have two issues here. 1.Transaction.objects.exclude(search_id=0) doesn't work. It does not take the value of variable search_id. 2.{{ transaction.{{ search_id }} }} in account_details.html doesn't work. I need to display data varying on user input. How do I use two variables inside a single tag in my template? Any help is appreciated. -
Django Invalid literal for Decimal: u'' when database has field values in embedded model field(Mango DB)
I created a user model in Django with an embeddedmodel location as i am using mangoDB. The location fields are decimal My form is from django import forms class StringListField(forms.CharField): def prepare_value(self, value): return ', '.join(value) def to_python(self, value): if not value: return [] return [item.strip() for item in value.split(',')] class ObjectListField(forms.CharField): def prepare_value(self, value): if not value: return '' newvalue = {} # for key, val in value.__dict__.items(): # if type(val) is unicode: # newvalue[key] = val newvalue['latitude']=value.latitude newvalue['longitude'] = value.longitude return ", ".join(["%s = %s" %(k,v) for k, v in newvalue.items()]) def to_python(self, value): if not value: return {} obj = {} lst = [item.strip() for item in value.split(',')] for item in lst: val = item.split('=') obj[val[0]] = val[1] return obj and the model is : from django.db import models from djangotoolbox.fields import ListField from djangotoolbox.fields import EmbeddedModelField from .forms import StringListField,ObjectListField # Create your models here. class CategoryField(ListField): def formfield(self, **kwargs): return models.Field.formfield(self, StringListField, **kwargs) class EmbeddedOverrideField(EmbeddedModelField): def formfield(self, **kwargs): return models.Field.formfield(self,ObjectListField,**kwargs) class User(models.Model): first_name = models.CharField(max_length=200) second_name = models.CharField(max_length=200) email = models.EmailField() location = EmbeddedOverrideField('location') # location = CategoryField() created_on = models.DateTimeField(auto_now_add=True) friends = CategoryField() def __str__(self): return self.first_name + " " + self.second_name class location(models.Model): … -
type object 'StudentPerformance' has no attribute 'objects'
Here is my code models.py class StudentPerformance(models.Model): student_activity=models.ForeignKey(StudentsActivity,db_index=True) student_subactivity=models.ForeignKey(StudentSubactivity,db_index=True) student_detail=models.ForeignKey(StudentDetail,db_index=True) grade_section=models.ForeignKey(UnitGradeSection,db_index=True) date=models.DateField(blank=True,null=True) venue=models.CharField(max_length=250,blank=True,null=True) remarks=models.CharField(max_length=250,blank=True,null=True) Views.py class StudentActivity(LoginRequiredMixin,TemplateView): template_name="student/student_activity.html" form_class2=PerformanceForm def get_context_data(self,*args,**kwargs): context=super(StudentActivity,self).get_context_data(*args,**kwargs) context['stud']=StudentDetail.objects.get(id=self.kwargs['stu_id']) context['vaccination']=VaccineMaster.objects.all() context['activity']=StudentsActivity.objects.all() context['subactivity']=StudentSubactivity.objects.all() context['form']=self.form_class context['form1']=self.form_class1 context['form2']=self.form_class2 return context def post(self,request,*args,**kwargs): self.context=super(StudentActivity,self).get_context_data(*args,**kwargs) if 'save' in request.POST: stu_ids=request.POST.get('stud_id[]') grade_ids=request.POST.get('grade_id[]') act=request.POST.get('act') subact=request.POST.get('sub') form=self.form_class2(self.request.POST) if form.is_valid(): date=form['date'].data venue=form['venue'].data remark=form['remarks'].data d=datetime.strptime(date,'%d-%m-%Y') perform,created=StudentPerformance.objects.get_or_create(student_activity_id=act,student_subactivity_id=subact,student_detail_id=stu_ids,grade_section_id=grade_ids,date=d,venue=venue,remarks=remark) if created: messages.success(request,'Details Entered Successfully') return HttpResponseRedirect('/student/student_activity/%s' %self.kwargs['stu_id']) else: message.error(request,'Nothing To save') return HttpResponseRedirect('') Iam getting an error like "type object 'StudentPerformance' has no attribute 'objects'" and cannot save the data to the database.Please help me to fix this error.Thank You. -
DjangoFilters-Filtering users from model
I'm using Django-Filters I make a dinamic filter, I'm trying to filter the users from "paciente" in the model "Medicard_rd". I figure how to filter the users from the other model "perfil". I put my models, views, and filters.py files. I need help, i can't figure the views.py queryset i have to use to filter those users in "Medicard_rd", and when i filter the users i want to show the fields "Titulo","hospital",etc. in the page. HELP me please. Models.py (the two models "Medicard_rd" and "perfil" models.py Filters.py from django.contrib.auth.models import User import django_filters class UserFilter(django_filters.FilterSet): class Meta: model = User fields = ['username', ]# 'first_name', 'last_name', ] Views.pyViews.p, like i said i figure only the "perfil" query model for users -
Django authenticate with active directory
My environment Django : 1.6.11 Python : 2.7.12 Package python-ldap : 2.4.39 django_auth_ldap : 1.2.12 My setting.py import ldap from django_auth_ldap.config import LDAPSearch, PosixGroupType AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) AUTH_LDAP_SERVER_URI = "ldap://domain.com:389" AUTH_LDAP_BIND_PASSWORD = "p@ssw0rd" AUTH_LDAP_SEARCH_DN = "OU=USERWEB,DC=DOMAIN,DC=COM" AUTH_LDAP_USER_SEARCH = LDAPSearch(AUTH_LDAP_SEARCH_DN, ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn" } This setting is example. LDAP Username : ldapadmin LDAP Pasword : p@ssw0rd My problem When I'm type username that has been create in AD already and click button for login it seem like can't connect to AD server because it return None of LDAP user My back-end authenticate function def login(request): logout(request) form = LoginForm() # If POST is given if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] ldap = ad().authenticate(username=username, password=password) if ldap is not None: if not user.is_active: form.errors['__all__'] = form.error_class([_('ERROR_USER_DISABLED')]) else: auth_login(request, user) request.session['foo'] = 'bar' # time to redirect url = request.GET.get('next') if url is None: url = reverse('dashboard') print "Leaving %s" % request.session.session_key return HttpResponseRedirect(url) else: form.errors['__all__'] = form.error_class([_('ERROR_USERNAME_PASSWORD_INCORRECT')]) return TemplateResponse(request, 'common/lock_screen.html', {'form': form, 'page_title': _('PAGE_TITLE_LOGIN')}) -
How to run django from python idle?
I know there are several softwares for Django like Pycharm,etc. But I want to know can I run a webpage created by Django from Python IDLE. Is there any way if there is please help me. -
how can i host my django website from Godaddy.com?
I have purchased the domain name and already rent the shared linux server from godaddy. So anyone please guide me how to host my website from there? -
Unable to read json object in Python function passed by javascript function--AJAX
I have been trying to send a json data strcuture to the python function (view.py). I am using Django framework. I have been successful in fetching the data from my textboxes and even store them. I can see that the relevant values get appended in the url too. But the problem arises when I try and read the value in my Python function which is corresponding to the next page. function submit_this(url) { var i,j;var arr=[]; for(i=0; i<Hello.length; i++){ arr[i]=[]; for(j=0;j<Hello[i].length; j++) { arr[i].push(document.getElementById(Hello[i][j]).value); } } xmlHttpReq = new XMLHttpRequest(); xmlHttpReq.open(\'POST\', url, true); xmlHttpReq.send(\'w=\' + encodeURI(arr));} </script></head><body> <form action=\"http://127.0.0.1:6000/params/button_click/\"> <center> <button id="submit_button" name="submit_button" onclick="submit_this(\'http://127.0.0.1:6000/params/button_click/\');" value="Submit">Submit </button> </center> </form> </body> </html> I tried reading the values by using cgi. form = cgi.FieldStorage() but I get to know that the form is empty. I realise I am pretty close as the data structure (arr) has successfully been appended in the url for the next page. I am just unable to read it. Any help would be really appreciated. Thanks. PS: Hello is also a Json object passed using a json file.