Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change admin password of a Django application after deploying it on pivotal cloud foundry?
I have deployed a simple blog application( using tutorials and python buildpack) using Django and deployed it on Pivotal Cloud Foundry. But I am unable to log in using the same admin credentials after it is in the cloud. How can I change the admin superuser credentials? -
Python function for getting a list of the past X months
Trying to make a template tag for my Django blog archive to show the last four months of the year, ie: <a>October 2017</a> <a>September 2017</a> <a>August 2017</a> <a>July 2017</a> I'm certain that it's so simple it's stupid but I'm just not getting it! Here's what I've got so far: @register.simple_tag def last_four_months(format): today = datetime.today() four_months = today - relativedelta(months=4) for month in four_months: return four_months.strftime(format) This throws a TypeError - 'datetime.datetime' object is not iterable -
Django/Python additional parameter causes internal server error
For class Notification I have @classmethod def notify(cls, msg_or_mid, target, sender=None, types=['SYS'], **kargs): that works if called as Notification.notify( msg, employee_from_user(solicitante), chamado=self.chamado.cache_numero, previsao=DateUtils.date_to_str(self.previsao_fim) ) but causes internal server error if called with an extra parameter, 'SYS': Notification.notify( msg, employee_from_user(solicitante), chamado=self.chamado.cache_numero, previsao=DateUtils.date_to_str(self.previsao_fim), 'SYS' ) Since I am a newbie I am completely lost. Any help is much appreciated. -
django how to implement a dynamic (bootstrap) modal
I'm trying to change the interaction of a page so that additional info about a product appears in a modal rather than an element that is shown/hidden when a button is clicked. the bit I'm not sure about is making the modal adapt it's contents to each product. Previously I had the template: <div class="item price-2 col-md-4 col-12 text-center best-buy"> <div class="item-inner"> <div class="heading"> <h3 class="title"><b>Cheapest</b></h3> </div> {% include 'components/quote_summary_item.html' with quote=first_quote %} </div><!--//item-inner--> </div><!--//item--> {% include 'components/quote_detail.html' with quote=first_quote %} Where quote_summary_item.html is: <div> <div class="quotes-summary"><img src="{{ quote.ImageUrl }}" alt=""></div> <p></p> <p >......... </p> <a class="btn btn-quote-primary" href="{% url 'users:profile %}">Select</a></div> <div class="content"> <p><b>Your Quote Details</b></p> <p>{{ quote.Name }}<br/> {{ quote.Type }} <br/> ..... </p> <button class="btn btn-cta-secondary" data-id="{{ quote.priceId }}">Info</button> </div><!--//content--> and quote_detail is: <div class="quote" id="quote{{ quote.priceId }}" style="display:none"> <div > <p><b>About this quote:</b></p> {{ quote.synopsisText|safe }} </div> <div class="row"> <div class="col"> <table class="table"> <thead class="til-table-head"> <tr> <th>Information</th> </tr> </thead> <tbody> <tr> <td></td> <td>{{ quote.Something }}</td> </tr> <tr> <td>Name</td> <td>{{ quote.Name }}</td> </tr> <tr> <td></td> <td>{{ quote.payType }}</td> </tr> ....... </tbody> </table> </div> </div> </div> And the .js used was: <script type="text/javascript"> $(document).ready(function () { $('.btn-cta-secondary').click(function (e) { var id = $(e.currentTarget).data('id') $('.quote').hide() $('#quote' + id).show() }) … -
Is set a param for CharField like upload_to param for FileField possible?
I have a WorkOrderUploadFile model like bellow: class WorkOrderUploadFile(models.Model): wo_num = models.CharField(max_length="16") filepath = models.CharField(max_length=128, default="images/qiyun_admin_servicemanage_workorder/") file = models.FileField(upload_to=generate_files_directory) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) You see, for the FileField there is a upload_to param, so I can use the generate_files_directory method to generate the file field value. Is is possible to set a method for CharField param? (because the wo_num CharField is need use a method to generate the number.) -
dynamic user form field populating with Django
I have a model: class ok(models.Model): name = models.CharField(max_length=255) project = models.CharField(max_length=255) story = models.CharField(max_length=500) depends_on = models.CharField(max_length=500, default='') rfc = models.CharField(max_length=255) I have model form. class okForm(ModelForm): class Meta: model = ok fields='__all__' I am getting first 3 fields: name, project, story from a backend api call. Now I want to populate the last two fields with respect to first three fields using AJAX call or jQuery or Javascript anything like that. I want to auto populate the last two fields from MySQL database in the front end itself before user submits the form. Kindly help. -
Create chat with WebSocket&Django, but without channels
I want to create chat with WebSocket and AJAX technologies and reconfigure Django's server to receive ws/wss protocols, but I need to do it without django-channels. I definitly don't understand channels' concepts, so I decided to work out with AJAX. I'm new to programming, so please be patient. -
filtering issue with a django template with two querysets - django
I have a dango template that I want to use to filter objects in a query sets. I have a group that I want ot add new members to. I have a list of member objects that are used to keep track of the groups members that were added when the group was created. The members were added by displaying a list of users friends with a checkbox next to their names. I now want to display a list of friends that are not already members of the group adn then add them to the group if they are selected. I am getting an issue with the html template filtering system that I have created to just show the list of friends that are not already members... can anyone help me figure this out. I have all the code below: here is the queries that were passed: # grab the group members members = Member.objects.filter(group = group).all() # grab all of the friends fo the logged in user friender = Friend.objects.filter(user = user.username).all() friended = Friend.objects.filter(friend = user).all() friends = friender | friended # the required parameters for this form parameters = { 'friends':friends, 'members':members, 'group':group, 'message':message, } return render(request, … -
Issue on Put method for creating a tracking option - Python
I want to create a tracking option ((i.e) Add tracking option) under the respective tracking category, using Xero tracking category API for my organisation. But while creating data using 'put' Requests method, it is not creating. I am using the below condition in python: response = requests.put(url=url, auth=oauth, data=xml_string) I want to know, what is the format for the data to be updated in the requests, for both content type xml/text and application/json. xml_string and url, I given is below: xml_string='<Option><Name>S11963</Name></Option>' url = 'https://api.xero.com/api.xro/2.0/TrackingCategories/{Tracking_Category}/Options' where Tracking_Category='620815a2-a7c6-4b85-8b01-ffb254ab34ad' Error: <ApiException xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\r\n <ErrorNumber>500</ErrorNumber>\r\n <Type>UnknownErrorException</Type>\r\n <Message>An error occurred in Xero. Check the API Status page http://status.developer.xero.com for current service status. Contact the API support team at api@xero.com for more assistance.</Message>\r\n</ApiException> Thanks -
Rendering/Redirecting Django in AJAX Success function
Trying my best to understand more between Django and Ajax but now I'm having a problem how to use (or what to use) between render to window.location.url in the ajax function. This is something along the lines of this similar question. To put it simply my situation is this: I'd like to pass a json to Django view so I used AJAX. "POST" Then from the url passed in AJAX it goes to view_routes view. I know that AJAX is expecting a response data so what I know is using HTTPResponse Problem: I want to pass routes (Objects) and routes_geojson (JSON) to the url where it will redirect to an HTML Page. (So I can use routes normally with {%%} tags and routes_geojson for its own purpose.) The said HTML page will also use view_routesviewif I usewindow.location.href = url`. How can I pass it from ajax? Use another ajax now with type:"GET"? Am I on the right track? Also if you have a suggested reading particulary on AJAX and Django that would be nice. :) Thank you! def view_routes(request, query=None): routes = None if query is None: routes = Route.objects.all() else: #View: Routes in Queried Boundary if request.method == 'POST': … -
Django clean password 'ValidationError' object has no attribute 'get'
I am using django-custom-user to make login with e-mail. I have 2 models CustomUser and ClientData: models.py class CustomUser(AbstractEmailUser): first_name = models.CharField(max_length=200, blank=True, null=True, default=None) last_name = models.CharField(max_length=200, blank=True, null=True, default=None) phone = models.CharField(max_length=20, blank=True, null=True, default=None) class ClientData(models.Model): user = models.OneToOneField(CustomUser) company = models.CharField(max_length=200, blank=True, null=True, default=None) bank_account = models.CharField(max_length=25, blank=True, null=True, default=None) I am trying to make a register form with both models and i have managed to do that, i have also made a clean password function, everything works, but when i purposely give 2 different password i get: 'ValidationError' object has no attribute 'get' forms.py class UserRegistrationForm(forms.ModelForm): email = forms.EmailField(required=True, max_length=150) first_name = forms.CharField(required=True, max_length=100) last_name = forms.CharField(required=True, max_length=100) password1 = forms.CharField(required=True, label='Password', max_length=100, widget=forms.PasswordInput()) password2 = forms.CharField(required=True, label='Confirm Password', max_length=100, widget=forms.PasswordInput()) phone = forms.CharField(required=True, max_length=20) class Meta: model = CustomUser fields = ['email', 'first_name', 'last_name', 'password1', 'password2', 'phone'] def clean(self): cleaned_data = super(UserRegistrationForm, self).clean() password1 = cleaned_data.get('password1') password2 = cleaned_data.get('password2') if password1 != password2: return forms.ValidationError('Password did not match.') return cleaned_data class UserDataRegistrationForm(forms.ModelForm): class Meta: model = ClientData fields = ['company', 'bank_account'] and this is the view i've made: views.py def register(request): data = dict() if request.method == 'POST': user_form = UserRegistrationForm(request.POST) data_form = UserDataRegistrationForm(request.POST) … -
How to make invisiable some item from select
I have Reporter model, and when I create News model, I have to choose reporter for this news, and I want to disappear Jimmy Olson from choose, but he must be in db, but not in choose list. how to make it? -
I want to return json response for manifest file in context processor request
I want to make a dynamic manifest file and provide on every page. For this i have to make json in manifest file dynamic. Solution which i have in my mind is to make a json response and provide through context processor.but how to pass content type in it. -
Strange GET requests to my site
In the last days, Google Analytics is showing me some strange GET methods that have been requested on my website. I have no clue if it is done by robots or humans or if it is some kind of attack or something harmless. It is coming from different countries, which for me is even more confusing because it seems like it is not only one person/robot. Some examples of these urls are: /en/?lipi=urn:li:page:d_flagship3_feed;ipLRICUhTrGXGdPXnW0tnQ== /en/?lipi=urn:li:page:d_flagship3_feed;3kcVPzepRVGxY7MZjonjig== /en/?lipi=urn:li:page:d_flagship3_feed;mFWFR+VMS0SHqJTkYN87EA== /en/?_sm_pdc=1&_sm_rid=7MV6JrjR5MSrPHJMDDrtjMMQZVz6lqJrH02kZVk Does anybody has an idea what that is? -
UpdateView in Django shows blank forms instead of Database previous data
I'm using UpdateView to edit data using forms. After I click edit the pop up using modal is showing the forms with blank data! It doesn't retrieve the previous data that was in the Database. Anyone know what should I add? I am stuck with this edit for about a week :( If anyone has a clue I will be greatful! Thank you! view.py- from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts = serverlist.objects.all() args = {'form' : form, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() if form.is_valid(): # Checks if validation of the forms passed post = form.save(commit=False) #if not form.cleaned_data['ServerName']: #post.servername = " " post.save() #text = form.cleaned_data['ServerName'] form = HomeForm() return redirect('serverlist') args = {'form': form, 'text' … -
Django admin interface FormAdmin not registering second Form override
I had an issue a while back with a clean() method, which is now working. But when I added a second Form into the mix, no code from that clean() method seems to fire at all. I tried copying the previous one that does work down to the last detail, but only the first one works. Here is the code: from django.contrib import admin from .models import Provider, Employer, Person, Learnership, Qualification, Unit_Standard, Alternate_Id_Type_Id from django import forms class PersonForm(forms.ModelForm): class Meta: model = Person fields = '__all__' def clean(self): person_alternate_id = self.cleaned_data.get('person_alternate_id') alternate_id_type_id = self.cleaned_data.get('alternate_id_type_id') if person_alternate_id is not None and alternate_id_type_id == 533: raise forms.ValidationError("Invalid Type ID") if person_alternate_id is None and alternate_id_type_id != 533: raise forms.ValidationError("Invalid Type ID") ... return self.cleaned_data class PersonAdmin(admin.ModelAdmin): form = PersonForm admin.site.register(Person, PersonAdmin) For reference, this one still works perfectly: class ProviderForm(forms.ModelForm): class Meta: model = Provider fields = '__all__' def clean(self): provider_start_date = self.cleaned_data.get('provider_start_date') provider_end_date = self.cleaned_data.get('provider_end_date') if provider_start_date > provider_end_date: raise forms.ValidationError("Start date can't be after end date") .... return self.cleaned_data class ProviderAdmin(admin.ModelAdmin): form = ProviderForm admin.site.register(Provider, ProviderAdmin) There don't appear to be any error messages at all, so I'm not sure how to debug it - there is just … -
Large Files Uploading on Angular 4+ to Django
Currently I am uploading file using angular2-http-file-upload and send it to django back-end and it work fine with small files here is how I done it but when uploading large file 35Mb-600Mb its throwing exception from django sometimes it run fine local server but on cloud it always throwing exception my-upload-item.ts import { UploadItem } from 'angular2-http-file-upload'; export class MyUploadItem extends UploadItem { constructor(file: any) { super(); this.url = 'http://127.0.0.1:8000/training/save/'; this.file = file; } } my-component.ts submit2() { // /////////////// // Upload File // /////////////// let uploadTrainingFile = (<HTMLInputElement>window.document.getElementById('fileInput1')).files[0]; console.log('file tarining ', uploadTrainingFile); let myUploadItem1 = new MyUploadItem(uploadTrainingFile); myUploadItem1.formData = { FormDataKey: 'Form Data Value', 'category': this.category, 'type': 'Training File' }; // (optional) form data can be sent with file this.uploaderService.onSuccessUpload = (item, response, status, headers) => { // success callback console.log('successs ', response.path, response.type); console.log('seed step') }; this.uploaderService.onErrorUpload = (item, response, status, headers) => { // error callback console.log('error ', response); }; this.uploaderService.onCompleteUpload = (item, response, status, headers) => { // complete callback, called regardless of success or failure console.log('callback ', response); }; this.uploaderService.onProgressUpload = (item, percentComplete) => { // progress callback console.log('progresss ', percentComplete) }; if (typeof uploadTrainingFile != 'undefined' ) { this.uploaderService.upload(myUploadItem1); console.log('uploaded'); // if (this.uploaderService.onProgressUpload) } … -
Check Google In App Subscription Renewal Status
I have to implement Google In App susbscription in my app. In server side, I want to validate subscription status of user. The response of subscription is as follow { "kind": "androidpublisher#subscriptionPurchase", "startTimeMillis": long, "expiryTimeMillis": long, "autoRenewing": boolean, "priceCurrencyCode": string, "priceAmountMicros": long, "countryCode": string, "developerPayload": string, "paymentState": integer, "cancelReason": integer, "userCancellationTimeMillis": long, "orderId": string } Google has api to validate subscription status. Its response is as follow. { "kind": "androidpublisher#subscriptionPurchase", "startTimeMillis": long, "expiryTimeMillis": long, "autoRenewing": boolean, "priceCurrencyCode": string, "priceAmountMicros": long, "countryCode": string, "developerPayload": string, "paymentState": integer, "cancelReason": integer, "userCancellationTimeMillis": long, "orderId": string } I want to check user subscription status by using this API. The question I want to ask how will I know that user subscription has been renewed by this response. If user get subscription for one month and after one month, subscription will be renewed automatically. I have receipt for old subscription in my database and I will be using same OrderId to check subscription status. How will I new that subscription has been renewed for that particular orderId. -
Delete Objects after Saving - Django
I have a problem about Delete Object after savings Django I have model Like: class Reaction(models.Model): REACT_TYPES = ( (LIKE, 'Like'), (LOVE, 'Love'), ) user = models.ForeignKey(User) react_type = models.CharField(max_length=100, choices=REACT_TYPES, default='LIKE') How can I write a def save() with: When saving, It will remove the available object with THE SAME user, react_type. If no have the same object, it will be created. My code is work!! def save(self, force_insert=False, force_update=False, *args, **kwargs): user = Reaction.objects.filter(user=self.user) react_type = Reaction.objects.filter(user=self.react_type) # Model delete if exist if self.id.exists() & self.react_type.exists() : self.Reaction.delete() # Model create if not exist else : self.Reaction.create() Sorry because I'm not good with Django. -
Role of kafka consumer, seperate service or Django component?
I'm designing a web log analytic. And I found an architect with Django(Back-end & front-end)+ kafka + spark. I also found some same system from this link:http://thevivekpandey.github.io/posts/2017-09-19-high-velocity-data-ingestion.html with below architect But I confuse about the role of kafka-consumer. It will is a service, independent to Django, right? So If I want to plot real-time data to front-end chart, how to I attached to Django. It will too ridiculous if I place both kafka-consumer & producer in Django. Request from sdk come to Django by pass to kafa topic (producer) and return Django (consumer) for process. Why we don't go directly. It looks simple and better. Please help me to understand the role of kafka consumer, where it should belong? and how to connect to my front-end. Thanks & best Regards, Jame -
Django get Data from API
i'm using Django Rest Framework (DRF) to build API in my project. And i want to get the data from API URL in my views.py. This is my services.py import requests import json def get_user(username, first_name): url = 'http://localhost:8000/api/v1/users/' # headers = {'Accept':'application/json', 'Content-Type':'application/json'} params = {'username': username, 'first_name': first_name} r = requests.get(url, params=params) data=str(r) user_list = json.dumps(data) return user_list and this is my views.py class test(APIView): permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] def get(self,request): lists = services.get_user('Fahmi', 'Fahmi') return Response({"success": True, "content": lists}) And i got an error below From postman : { "content": "\"<Response [401]>\"", "success": true } From terminal : "GET /api/v1/users/?username=Fahmi&first_name=Fahmi HTTP/1.1" 401 58 What is wrong in my code? -
ModuleNotFoundError: Trying to import model from models folder into a view in views folder
I am new to the Django framework and I have some questions regarding importing of modules. Below is my file structure: MyLife - MyLife - finance - models - __init__.py - category.py - views - __init__.py - category.py I am trying to import the models.category into my views.category. models.__init__.py: from .base_model import BaseModel from .category import Category from .client import Client from .entry import Entry from .rule import Rule from .wish_list_item import WishListItem __all__ = ['BaseModel', 'Category', 'Client', 'Entry', 'Rule', 'WishListItem'] views.category.py: from django.shortcuts import render from MyLife.finance.models import Category def category(request): all_categories = Category.objects.all() return render(request, 'finance/category.html', {'list_categories': all_categories}) models.category.py: from django.db import models from .base_model import BaseModel class Category(BaseModel): description = models.CharField(max_length=50) def __str__(self): return self.description Here is my stack trace error: File "/Users/AKJ/Coding/MyLife/MyLife/finance/urls.py", line 3, in <module> from . import views File "/Users/AKJ/Coding/MyLife/MyLife/finance/views/__init__.py", line 3, in <module> from . category import category File "/Users/AKJ/Coding/MyLife/MyLife/finance/views/category.py", line 3, in <module> from MyLife.finance.models import Category ModuleNotFoundError: No module named 'MyLife.finance' I am not sure what is wrong and if i am missing something out. I heard a lot about init.py to help reduce the namespace, however, i seem to have problems and i do not really understand the other stackoverflow … -
Using https as standard with django project
I am learning django and trying to complete my first webapp. I am using shopify api & boilder plate (starter code) and am having an issue with the final step of auth. Specifically, the redirect URL -- it's using HTTP:// when it should NOT and I don't know how to change it.. #in my view def authenticate(request): shop = request.GET.get('shop') print('shop:', shop) if shop: scope = settings.SHOPIFY_API_SCOPE redirect_uri = request.build_absolute_uri(reverse('shopify_app_finalize')) #try this with new store url? print('redirect url', redirect_uri) # this equals http://myherokuapp.com/login/finalize/ permission_url = shopify.Session(shop.strip()).create_permission_url(scope, redirect_uri) return redirect(permission_url) return redirect(_return_address(request)) Which is a problem because my app uses the Embedded Shopify SDK which causes this error to occur at the point of this request Refused to frame 'http://my.herokuapp.com/' because it violates the following Content Security Policy directive: "child-src 'self' https://* shopify-pos://*". Note that 'frame-src' was not explicitly set, so 'child-src' is used as a fallback. How do i change the URL to use HTTPS? Thank you so much in advance. Please let me know if I can share any other details but my code is practically identical to that starter code -
how to upload image to django application from android using okhttp3
File sourceFile = new File(str_image); Log.d("TAG", "File...::::" + sourceFile + " : " + sourceFile.exists()); final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpeg"); String filename = str_image.substring(str_image.lastIndexOf("/")+1); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("listing_image", filename, RequestBody.create(MEDIA_TYPE_PNG, new File(str_image)) .addFormDataPart("bussinessName", str_businessName) .addFormDataPart("services",str_Services) .addFormDataPart("create_new","1") .addFormDataPart("referer",str_referer) .addFormDataPart("link","-1") .build(); Request request = new Request.Builder() .url(URL_UPLOAD_IMAGE) .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); String res = response.body().string(); Log.e("TAG", "Error: " + res); return new JSONObject(res); This my uploading code using okhttp in android app And Below code is the request header when i am trying to upload image from web interface. Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8 Accept-Encoding:gzip, deflate Accept-Language:en-US,en;q=0.8 Cache-Control:no-cache Connection:keep-alive Content-Length:2867997 Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryNgoNfg2kEYAAQDeH Here i am uploading the image to django rest api -
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc7 in position 27: invalid continuation byte django
I'm trying to upload my django project to Google Cloud Platform. When I run python manage.py runserver an error occurs. Until a while ago, it worked well. After fixing codes of just one file 'setting.py' the error occurred. Here's a screenshot image below. I did my best to find the solution on Google and Stackoverflow, and I tried hard for find something wrong in my code, but I couldn't find anything. Here's my directory structure, my main codes, and Project interpreter settings below. (Because I never changed other codes in my project and the amount of codes are too many, I won't upload all the codes in my django project.) views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse("Hello, world!") urls.py from django.conf.urls import url from django.contrib import admin from my_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home) ] settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 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 = 'secret …